Im trying to insert into my database (Oracle 12c) table a new entry but im failing to do that
The following is my entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Divisions
*
* #ORM\Table(name="DIVISIONS")
* #ORM\Entity
*/
class Divisions
{
/**
* #var int
*
* #ORM\Column(name="DIVISIONID", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="DIVISIONS_DIVISIONID_seq", allocationSize=1, initialValue=1)
*/
public $divisionid = '"SPECIFICATIONS"."ISEQ$$_79111".nextval';
/**
* #var string|null
*
* #ORM\Column(name="DIVISIONNAME", type="string", length=500, nullable=true)
*/
public $divisionname;
/**
* #var int|null
*
* #ORM\Column(name="SORTORDER", type="integer", nullable=true, options={"default"="1"})
*/
public $sortorder = '1';
/**
* #var int|null
*
* #ORM\Column(name="ISDELETED", type="integer", nullable=true)
*/
public $isdeleted = '0';
public function getDivisionid(): ?int
{
return $this->divisionid;
}
public function getDivisionname(): ?string
{
return $this->divisionname;
}
public function setDivisionname(?string $divisionname): self
{
$this->divisionname = $divisionname;
return $this;
}
public function getSortorder(): ?int
{
return $this->sortorder;
}
public function setSortorder(?int $sortorder): self
{
$this->sortorder = $sortorder;
return $this;
}
public function getIsdeleted(): ?int
{
return $this->isdeleted;
}
public function setIsdeleted(?int $isdeleted): self
{
$this->isdeleted = $isdeleted;
return $this;
}
}
And here is my controller that is trying to "POST" and add a new Division
<?php
namespace App\Controller;
use App\Entity\Divisions;
use App\Form\DivisionsType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* #Route("api/divisions")
*/
class DivisionsController extends AbstractController
{
/**
* #Route("", name="divisions_add", methods={"POST"})
*/
public function addDivisions(Request $request)
{
$em = $this->getDoctrine()->getManager();
$division = new Divisions();
$division->setDivisionname('TestDiv');
$em->persist($division);
$em->flush();
return new Response(
Response::HTTP_OK
);
}
}
when i try to call this the following Error message will appear:
An exception occurred while executing 'INSERT INTO DIVISIONS (DIVISIONID, DIVISIONNAME, SORTORDER, ISDELETED) VALUES (?, ?, ?, ?)' with params [16, "TestDiv", "1", "0"]:
ORA-32795: cannot insert into a generated always identity column
For some reason no matter what i try the DivisionID column will be called.. is there a way to insert without calling some certain columns?
Or is there a way to send it as 'INSERT INTO DIVISIONS (DIVISIONNAME, SORTORDER, ISDELETED) VALUES (?, ?, ?)' with params ["TestDiv", "1", "0"]'
PS: Entity is auto generated from database
If anybody wants more info ill happily provide
Ok so if anybody reaches this point and is still stuck i find kind of a work around:
I changed my Entity to look like that:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Divisions
*
* #ORM\Table(name="DIVISIONS")
* #ORM\Entity
*/
class Divisions
{
/**
* #var int
*
* #ORM\Column(name="DIVISIONID", type="integer", nullable=false)
* #ORM\Id
*/
public $divisionid;
/**
* #var string|null
*
* #ORM\Column(name="DIVISIONNAME", type="string", length=500, nullable=true)
*/
public $divisionname;
/**
* #var int|null
*
* #ORM\Column(name="SORTORDER", type="integer", nullable=true, options={"default"="1"})
*/
public $sortorder = '1';
/**
* #var int|null
*
* #ORM\Column(name="ISDELETED", type="integer", nullable=true)
*/
public $isdeleted = '0';
public function getDivisionid(): ?int
{
return $this->divisionid;
}
public function getDivisionname(): ?string
{
return $this->divisionname;
}
public function setDivisionname(?string $divisionname): self
{
$this->divisionname = $divisionname;
return $this;
}
public function getSortorder(): ?int
{
return $this->sortorder;
}
public function setSortorder(?int $sortorder): self
{
$this->sortorder = $sortorder;
return $this;
}
public function getIsdeleted(): ?int
{
return $this->isdeleted;
}
public function setIsdeleted(?int $isdeleted): self
{
$this->isdeleted = $isdeleted;
return $this;
}
}
Then in the Controller i added the following function:
private function getMaxDivisionIdNumber() {
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT MAX(u.divisionid) FROM App\Entity\Divisions u');
$res = $query->getResult();
return $res[0][1];
}
Now this function is used to get the Max id number.. so my controller would look something like that:
<?php
namespace App\Controller;
use App\Entity\Divisions;
use App\Form\DivisionsType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* #Route("api/divisions")
*/
class DivisionsController extends AbstractController
{
/**
* #Route("", name="divisions_add", methods={"POST"})
*/
public function addDivisions(Request $request)
{
$em = $this->getDoctrine()->getManager();
$content = $request->getContent();
$content = json_decode($content);
$division = new Divisions();
foreach ($content as $key => $value) {
$division->$key = $value;
}
$maxId = (int) $this->getMaxDivisionIdNumber();
$division->divisionid = $maxId + 1;
$em->persist($division);
$em->flush();
return new Response(
Response::HTTP_OK
);
}
private function getMaxDivisionIdNumber() {
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT MAX(u.divisionid) FROM App\Entity\Divisions u');
$res = $query->getResult();
return $res[0][1];
}
}
Related
this is my repository, i wrote the function showActive() in there but when i try to call it on my controller it says that it is not defined.
<?php
namespace App\Repository;
use App\Entity\Pais;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #method Pais|null find($id, $lockMode = null, $lockVersion = null)
* #method Pais|null findOneBy(array $criteria, array $orderBy = null)
* #method Pais[] findAll()
* #method Pais[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PaisRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Pais::class);
}
/**
* #return pais[]
*/
public function showActive(){
$em = $this->getEntityManager();
$q = $em->createQuery('
SELECT pa
FROM App\Entity\Pais pa
WHERE pa.activo <= 1
');
}
heres my controller
<?php
namespace App\Controller;
use App\Entity\Pais;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ListController extends AbstractController
{
/**
* #Route("/lista", name="lista")
*/
public function show(): Response {
$pais = $this->getDoctrine()->getRepository(Pais::class)->showActive();
return $this->render("main/lista.html.twig",array('paises'=>$pais));
}
}
am i missing something? i didn't find anything in the documentation
i tried to add use App\Repository\PaisRepository but it didn't fix it.
sorry for the probably dumb question.
Edit: here is my Pais entity.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pais
*
* #ORM\Table(name="pais", uniqueConstraints={#ORM\UniqueConstraint(name="abrev", columns={"abrev"})})
* #ORM\Entity(repositoryClass="App\Repository\PaisRepository")
*
*/
class Pais
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="descripcion", type="string", length=100, nullable=false)
*/
private $descripcion;
/**
* #var string
*
* #ORM\Column(name="abrev", type="string", length=10, nullable=false)
*/
private $abrev;
/**
* #var bool
*
* #ORM\Column(name="activo", type="boolean", nullable=false, options={"default"="1"})
*/
private $activo = true;
public function getId(): ?int
{
return $this->id;
}
public function getDescripcion(): ?string
{
return $this->descripcion;
}
public function setDescripcion(string $descripcion): self
{
$this->descripcion = $descripcion;
return $this;
}
public function getAbrev(): ?string
{
return $this->abrev;
}
public function setAbrev(string $abrev): self
{
$this->abrev = $abrev;
return $this;
}
public function getActivo(): ?bool
{
return $this->activo;
}
public function setActivo(bool $activo): self
{
$this->activo = $activo;
return $this;
}
}
Can you try to change your repository declaration in your entity as follow:
* #ORM\Entity(repositoryClass=App\Repository\PaisRepository::class)
In your entity:
<?php
namespace App\Entity;
use App\Repository\PaisRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* Pais
*
* #ORM\Table(name="pais", uniqueConstraints={#ORM\UniqueConstraint(name="abrev", columns={"abrev"})})
* #ORM\Entity(repositoryClass=PaisRepository::class)
*
*/
class Pais
And try to clear cache after that.
I am using a service within twig like this
{{ count_service.getCount(term.getId) }}
I want the service to use a repository function, repository function
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping;
class SynonymRepository extends EntityRepository
{
public function getCount($termId)
{
$qbSynonymType = $this->getEntityManager()->createQueryBuilder();
$synonymTypes = $qbSynonymType->select('synonymType.id, synonymType.type')
->from('AppBundle:SynonymType', 'synonymType')
->getQuery()->getResult();
$qb = $this->getEntityManager()->createQueryBuilder();
$count = [];
$qb->select('count(synonym.synonymId)')
->from('AppBundle:Synonym','synonym');
foreach($synonymTypes as $type) {
$count[$type['type']] = $qb
->where('synonym.term = :termId')
->andWhere('synonym.synonymType = :type')
->setParameter('termId', $termId)
->setParameter('type', $type['id'])
->getQuery()->getSingleScalarResult();
}
$qbTerm = $this->getEntityManager()->createQueryBuilder()->from('AppBundle:Term', 'term');
$count['parent'] = "NaN";
$count['children'] = "NaN";
return $count;
}
}
My service.yml looks like this
synonymrepository:
class: Doctrine\ORM\EntityRepository
factory: ["#doctrine.orm.entity_manager", getRepository]
arguments:
- AppBundle\Entity\SynonymType
term_count:
class: AppBundle\Services\TermCount
arguments:
- "#synonymrepository"
And finally my service looks like this
<?php
namespace AppBundle\Services;
use AppBundle\Repository\SynonymRepository;
class TermCount
{
private $repository;
public function __construct()
{
$this->repository = new SynonymRepository();
}
public function getCount($termId)
{
return $this->repository->getCount($termId);
}
}
When running this I am getting the following error
Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 0 passed in /var/www/html/src/AppBundle/Services/TermCount.php on line 15 and exactly 2 expected
I assume this is happening because extending SynonymRepository with the EntityRepository requires EntityManagerInterface $em and Mapping\ClassMetadata $class. But I am not sure how pass them to EntityRepository.
I was using this answer to get me here, lost on how to actually implement the finall bit.
Thanks for helping.
UPDATE
Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Table(name="synonym")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SynonymRepository")
*/
class Synonym
{
/**
* #var int
* #ORM\Id()
* #ORM\Column(name="synonym_id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $synonymId;
/**
* #var Term
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Term", inversedBy="synonyms")
*/
protected $term;
/**
* #var SynonymType[]
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\SynonymType", inversedBy="synonyms")
*/
protected $synonymType;
/**
* #var int
* #ORM\Column(name="language_id", type="integer")
*/
protected $languageId;
/**
* #var string
* #ORM\Column(name="synonym", type="string", length=255)
*/
protected $synonym;
public function __construct()
{
// $this->synonymType = new ArrayCollection();
}
/**
* #return int
*/
public function getSynonymId(): int
{
return $this->synonymId;
}
/**
* #return Term
*/
public function getTerm(): Term
{
return $this->term;
}
/**
* #param int $termId
* #return Term
*/
public function setTerm(int $termId): Term
{
$this->term = $termId;
return $this->term;
}
/**
* #return SynonymType[]
*/
public function getSynonymType()
{
return $this->synonymType;
}
/**
* #param SynonymType $synonymType
* #return SynonymType
*/
public function setSynonymType(SynonymType $synonymType): SynonymType
{
$this->synonymType = $synonymType;
return $this->synonymType;
}
/**
* #return int
*/
public function getLanguageId(): int
{
return $this->languageId;
}
/**
* #param int $languageId
* #return Synonym
*/
public function setLanguageId(int $languageId): Synonym
{
$this->languageId = $languageId;
return $this;
}
/**
* #return string
*/
public function getSynonym(): string
{
return $this->synonym;
}
/**
* #param string $synonym
* #return Synonym
*/
public function setSynonym(string $synonym): Synonym
{
$this->synonym = $synonym;
return $this;
}
}
You need to use DI (Dependency injection) in your construct insted of using new cause as i see the erreur your SynonymRepository depends on other services
<?php
namespace AppBundle\Services;
use AppBundle\Repository\SynonymRepository;
class TermCount
{
private $repository;
public function __construct(SynonymRepository $synonymRepository)
{
$this->repository = $synonymRepository;
}
public function getCount($termId)
{
return $this->repository->getCount($termId);
}
}
In Symfony4 I have a repository :
<?php
namespace App\Repository;
use App\Entity\Comment;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
class CommentRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Comment::class);
}
public function findByNews($news)
{
return $this->createQueryBuilder('c')
->where('c.news = :news')
->setParameter('news', $news)
//->setMaxResults(10)
->getQuery()
->getResult()
;
}
}
When I try to use it in this action of my ajax controller:
public function comments(Request $request)
{
if ($request->isXmlHttpRequest()) {
$newsId = $request->get('id');
$newsRepository = $this->getDoctrine()->getRepository(News::class);
$news = $newsRepository->find($newsId);
$commentRepository = $this->getDoctrine()->getRepository(Comment::class);
$comments = $commentRepository->findByNews($news);
$comments = 0;
$serializer = $this->get('serializer');
$response = $serializer->serialize($comments, 'json');
return new JsonResponse(array('data' => $response));
}
return new Response("Error : this is not an ajax request!", 400);
}
I get this error :
Uncaught PHP Exception RuntimeException: "The "App\Entity\Comment" entity has a repositoryClass set to "App\Entity\CommentRepository", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "doctrine.repository_service"." at (...)\vendor\doctrine\doctrine-bundle\Repository\ContainerRepositoryFactory.php line 82
I can't see why the CommentRepository is not valid.
And why this is mentionning App\Entity\CommentRepository instead of App\Repository\CommentRepository?
Any idea ?
Edit :
Here's the Comment entity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MemberBundle\Entity\Comment
*
* #ORM\Table(name="comment")
* #ORM\Entity(repositoryClass="App\Entity\CommentRepository")
*/
class Comment
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var App\Entity\News $news
*
* #ORM\ManyToOne(targetEntity="App\Entity\News")
* #ORM\JoinColumn(name="news", referencedColumnName="id", onDelete="CASCADE")
*/
private $news;
/**
* #var App\Entity\User $author
*
* #ORM\ManyToOne(targetEntity="App\Entity\User")
* #ORM\JoinColumn(name="author", referencedColumnName="id", onDelete="CASCADE")
*/
private $author;
/**
* #var text $content
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var datetime $date
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
public function __construct() {
$this->date = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set news
*
* #param App\Entity\News $news
*/
public function setNews($news)
{
$this->news = $news;
}
/**
* Get news
*
* #return App\Entity\News
*/
public function getNews()
{
return $this->news;
}
/**
* Set author
*
* #param App\Entity\User $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* Get author
*
* #return App\Entity\User
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set content
*
* #param text $content
*/
public function setContent($content)
{
$this->content = $content;
}
/**
* Get content
*
* #return text
*/
public function getContent()
{
return $this->content;
}
/**
* Set date
*
* #param datetime $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* Get date
*
* #return datetime
*/
public function getDate()
{
return $this->date;
}
}
You should change #ORM\Entity(repositoryClass="App\Entity\CommentRepository") to #ORM\Entity(repositoryClass="App\Repository\CommentRepository")
You could otherwise move CommentRepositoryinto Entity directory (and update the namespace accordingly), but it's best to follow the standard structure and keep your repositories in the App\Repository namespace.
Here is my Insert Query, how can I tell that, created_at(current time-stamp), is_active(default 1) set in the mysql db structure needs to be taken.
When I omit the $question->setCreatedAt($this->createdAt); in the insert operation it shows me an Integrity constraint violation, do you know what is the issue?
In the Questions table:
question:
id
question
created_by
created_at
modified_by
modified_at
is_Active
Entity:
<?php
namespace Library\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Base class for all the Entities
* This class maps id, active, created and modified columns
*
* #author
*/
/**
* #ORM\MappedSuperclass
*/
class BaseEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(name="id", type="integer")
* #var integer
*/
protected $id;
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active;
/**
* #ORM\Column(name="created_at", type="datetime")
* #var datetime
*/
protected $createdAt;
/**
* #ORM\Column(name="created_by", type="integer", nullable=true)
* #var integer
*/
protected $createdBy;
/**
* #ORM\Column(name="modified_at", type="datetime")
* #var datetime
*/
protected $modifiedAt;
/**
* #ORM\Column(name="modified_by", type="integer")
* #var integer
*/
protected $modifiedBy;
public function getId() {
return $this->id;
}
public function getActive() {
return $this->active;
}
public function getCreatedAt() {
return $this->createdAt;
}
public function getCreatedBy() {
return $this->createdBy;
}
public function getModifiedAt() {
return $this->modifiedAt;
}
public function getModifiedBy() {
return $this->modifiedBy;
}
public function setId($id) {
$this->id = $id;
}
public function setActive($active) {
$this->active = $active;
}
public function setCreatedAt($createdAt) {
$this->createdAt = $createdAt;
}
public function setCreatedBy($createdBy) {
$this->createdBy = $createdBy;
}
public function setModifiedAt($modifiedAt) {
$this->modifiedAt = $modifiedAt;
}
public function setModifiedBy($modifiedBy) {
$this->modifiedBy = $modifiedBy;
}
}
This is my Question Entity:
<?php
namespace Survey\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Library\Entity\BaseEntity;
use Survey\Entity\Survey;
/**
* Description of Survey Questions
*
* #author Mubarak
*/
/**
* #ORM\Entity
* #ORM\Table(name="survey_questions")
*/
class Question extends BaseEntity{
/**
* #ORM\Column(name="question", type="string")
* #var string
*/
protected $question;
/**
* #ORM\ManyToOne(targetEntity="Survey\Entity\Survey", inversedBy="questions")
* #ORM\JoinColumn(name="survey_id", referencedColumnName="id")
*/
private $surveys;
public function getQuestion() {
return $this->question;
}
public function setQuestion($question) {
$this->question = $question;
}
public function getSurveys() {
return $this->surveys;
}
// public function setSurveys(ArrayCollection $survey) {
public function setSurveys(Survey $surveys = null) {
$this->surveys = $surveys;
}
// public function __toString() {
// return __CLASS__ . ": [id: {$this->id}, name: {$this->name}]";
// }
}
Here is my insert Operation:
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setCreatedAt($this->createdAt);
$question->setModifiedBy($userId);
$question->setModifiedAt($this->modifiedAt);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}
This is Ok, its working properly, but i dont want to insert the Created_at, modified_at
public function insertQuestion($userId, $survey, $questionArr) {
try{
$question = new Question();
$question->setQuestion($questionArr['question']);
$question->setSurveys($survey);
$question->setActive(1);
$question->setCreatedBy($userId);
$question->setModifiedBy($userId);
$this->entityManager->persist($question);
$this->entityManager->flush();
return $question;
}catch(Exception $ex){
throw new Exception("Couldnt insert the question");
}
}
If you want to set default values it is best to set them in your object model where possible.
/**
* #ORM\Column(name="is_active", type="boolean")
* #var boolean
*/
protected $active = true;
For time-stamps though it is a bit of a different story...
I would suggest to take a look at the Gedmo doctrine extensions library which includes solutions for createdAt and other common columns for your model. No need to reinvent the wheel... .
How to write request for loading all users from DB by user role?
I am using three tables (users, role and user_role) with many-to-many relations.
If you can help mе to write function loadUsersByRole() in UserRepository i I would be very grateful.
Entity\User
namespace Kombinator\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Kombinator\UserBundle\Entity\User
*
* #ORM\Table(name="kombinator_users")
* #ORM\Entity(repositoryClass="Kombinator\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\ManyToOne(targetEntity="Company")
* #ORM\JoinColumn(name="company", referencedColumnName="id")
*/
protected $company;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getRoles()
{
return $this->roles->toArray();
}
public function getRole()
{
$roles=$this->roles->toArray();
if(isset($roles[0])){return $roles[0];}
else{return NULL;}
}
...
UserRepository
namespace Kombinator\UserBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Kombinator\UserBundle\Controller\Paginator;
use Kombinator\UserBundle\Entity\Filter;
use Kombinator\UserBundle\Entity\Role;
/**
* UserRepository
*/
class UserRepository extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$q = $this
->createQueryBuilder('u')
->select('u, r')
->leftJoin('u.roles', 'r')
->where('u.email = :email AND u.status = 1')
->setParameter('email', $username)
->getQuery();
try {
$user = $q->getSingleResult();
} catch (NoResultException $e) {
$message = sprintf('Unable to find an active ... by "%s".',$username);
throw new UsernameNotFoundException($message, 0, $e);
}
return $user;
}
public function findAllActiveJoinedToCompany($company)
{
$query = $this->getEntityManager()
->createQuery('
SELECT p, c FROM KombinatorUserBundle:User p
JOIN p.company c WHERE p.company='.$company);
try {
return $query;
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
Entity\Role
namespace Kombinator\UserBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="kombinator_role")
* #ORM\Entity()
*/
class Role implements RoleInterface
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set role
*
* #param string $role
* #return Role
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Add users
*
* #param \Kombinator\UserBundle\Entity\User $users
* #return Role
*/
public function addUser(\Kombinator\UserBundle\Entity\User $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* #param \Kombinator\UserBundle\Entity\User $users
*/
public function removeUser(\Kombinator\UserBundle\Entity\User $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
RoleRepository
namespace Kombinator\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* RoleRepository
*/
class RoleRepository extends EntityRepository
{
public function findAll()
{
$query = $this->getEntityManager()
->createQuery('
SELECT p FROM KombinatorUserBundle:Role p
ORDER BY p.id'
);
try {
return $query->getResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
}
When many-to-many relationship is involved you should use MEMBER OF clause in your query:
public function loadUsersByRole($roleId)
{
$q = $this
->createQueryBuilder('u')
->select('u, r')
->leftJoin('u.roles', 'r')
->where(':roleId MEMBER OF u.roles AND u.status = 1')
->setParameter('roleId', $roleId)
->getQuery();
return $q->getResult();
}