Multiple joins in a ManyToMany relation - symfony

I have 3 entities, User, Parking and Voiture.
User had a ManyToMany relation with parking while Parking has a OneToMany reamtion with voiture.
what I'm trying to do:
Get the cars (voitures) that belong to all parkings the currect user is related to
how I'm trying to do it:
Using querybuilder, but I still don't know how to make it work
here are my entities
Entity User:
<?php
/**
* #ORM\Entity
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
/**
* #ORM\Column(type="string", length=191, unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Parking", mappedBy="agents")
*/
private $parkings;
public function __construct()
{
$this->parkings = new ArrayCollection();
}
/**
* #return Collection|Parking[]
*/
public function getParkings(): Collection
{
return $this->parkings;
}
public function addParking(Parking $parking): self
{
if (!$this->parkings->contains($parking)) {
$this->parkings[] = $parking;
$parking->addAgent($this);
return $this;
}
return $this;
}
public function removeParking(Parking $parking): self
{
if ($this->parkings->contains($parking)) {
$this->parkings->removeElement($parking);
$parking->removeAgent($this);
}
return $this;
}
}
Entity Parking:
<?php
/**
* #ORM\Entity(repositoryClass="App\Repository\ParkingRepository")
*/
class Parking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\user", inversedBy="parkings")
*/
private $agents;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Voiture", mappedBy="parking", orphanRemoval=true)
*/
private $voitures;
public function __construct()
{
$this->agents = new ArrayCollection();
$this->voitures = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* #return Collection|user[]
*/
public function getAgents(): Collection
{
return $this->agents;
}
public function addAgent(user $agent): self
{
if (!$this->agents->contains($agent)) {
$this->agents[] = $agent;
}
return $this;
}
public function removeAgent(user $agent): self
{
if ($this->agents->contains($agent)) {
$this->agents->removeElement($agent);
}
return $this;
}
/**
* #return Collection|Voiture[]
*/
public function getVoitures(): Collection
{
return $this->voitures;
}
public function addVoiture(Voiture $voiture): self
{
if (!$this->voitures->contains($voiture)) {
$this->voitures[] = $voiture;
$voiture->setParking($this);
}
return $this;
}
public function removeVoiture(Voiture $voiture): self
{
if ($this->voitures->contains($voiture)) {
$this->voitures->removeElement($voiture);
// set the owning side to null (unless already changed)
if ($voiture->getParking() === $this) {
$voiture->setParking(null);
}
}
return $this;
}
}
And Entity Voiture
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\VoitureRepository")
*/
class Voiture
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $matricule;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="voitures")
* #ORM\JoinColumn(nullable=false)
*/
private $parking;
/**
* #ORM\Column(type="boolean")
*/
private $parked;
public function getId(): ?int
{
return $this->id;
}
public function getMatricule(): ?string
{
return $this->matricule;
}
public function setMatricule(string $matricule): self
{
$this->matricule = $matricule;
return $this;
}
public function getParking(): ?Parking
{
return $this->parking;
}
public function setParking(?Parking $parking): self
{
$this->parking = $parking;
return $this;
}
}

I propose to add an intermediate entity UserParking between User and Parking entities.
So we have a OneToMany relationship between User and UserParking and a OneToMany relationship between Parking and UserParking instead of ManyToMany relationship between User and Parking.
The entities will be similar to code below:
Entity User:
<?php
/**
* #ORM\Entity
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
/**
* #ORM\Column(type="string", length=191, unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserParking", mappedBy="agent")
* #ORM\JoinColumn(nullable=true)
*/
private $user_parking;
// getter and setter
}
Entity Parking:
<?php
/**
* #ORM\Entity(repositoryClass="App\Repository\ParkingRepository")
*/
class Parking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserParking", mappedBy="parking")
* #ORM\JoinColumn(nullable=true)
*/
private $user_parking;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Voiture", mappedBy="parking", orphanRemoval=true)
*/
private $voitures;
// getters and setters
}
Entity UserParking
/**
* UserParking
*
* #ORM\Table(name="user_parking")
* #ORM\Entity(repositoryClass="App\Repository\UserParkingRepository")
*/
class UserParking
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="user_parking")
* #ORM\JoinColumn(nullable=false)
*/
private $agent;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="user_parking")
* #ORM\JoinColumn(nullable=false)
*/
private $parking;
// getter and setter
}
And Entity Voiture
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\VoitureRepository")
*/
class Voiture
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $matricule;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="voitures")
* #ORM\JoinColumn(nullable=false)
*/
private $parking;
/**
* #ORM\Column(type="boolean")
*/
private $parked;
}
So to get the cars (voitures) that belong to all parkings the current user is related to you need to:
1- Get the current user object.
2- Get the UserParking array from the user object .
3- Get the Parking objects from the UserParking array.
4- Get the cars from the Parking objects.
The code will be similar to this:
$em = $this->getDoctrine()->getManager();
/* Get user from the session */
$user = $this->getUser();
$userParkings = $user->getUserParking();
$parkings = [];
foreach ($userParkings as $item) {
$parking = $item->getParking();
$parkings[count($parkings)] = $parking;
}
// you can get voitures from parkings

Start from Voiture entity and inner join the Parking and User entities using their associations:
$queryBuilder = $this->getDoctrine()->getRepository('App:Voiture')->createQueryBuilder('v');
$queryBuilder->innerJoin('v.parking', 'p');
$queryBuilder->innerJoin('v.agents', 'a');
Finally, you can filter on the relation either through a condition:
$queryBuilder->where('a.id = :userId');
$queryBuilder->setParameter("userId", 1);
$cars = $queryBuilder->getQuery()->getResult();
or place the condition on the $queryBuilder->innerJoin('v.agents', 'a', 'WITH', 'a.id = :userId'); see doctrine inner join with condition
References
SQL join: where clause vs. on clause

Related

Missing value for primary key id on App\Entity symfony

My relation between 2 entities is a OneToOne relation.
1) User Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
class User
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var $userContact
*
* #ORM\OneToOne(targetEntity="UserContact" , inversedBy="User")
* #ORM\JoinColumn(name="id", referencedColumnName="user_id", nullable=false)
**/
private $userContact;
/**
* #ORM\Column(type="string", length=255)
*/
private $last_name;
public function getId()
{
return $this->id;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
}
UserContact Entity:
class UserContact
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="integer")
*/
private $user_id;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="UserContact")
*/
private $user;
/**
* #ORM\Column(type="string", length=255)
*/
private $mobile_number;
public function getId()
{
return $this->id;
}
public function getUserId(): ?int
{
return $this->user_id;
}
public function setUserId(int $user_id): self
{
$this->user_id = $user_id;
return $this;
}
public function getMobileNumber(): ?string
{
return $this->mobile_number;
}
public function setMobileNumber(string $mobile_number): self
{
$this->mobile_number = $mobile_number;
return $this;
}
}
My User Repository looks like this:
class UserRepository extends ServiceEntityRepository
{
public function index() {
return $this->createQueryBuilder('u')
->innerJoin('u.userContact', 'uc')
->getQuery()
->execute();
}
}
And the controller looks like this:
public function index()
{
$users = $em->getRepository('App:User')->index();
}
It's throwing an error like this one:
Missing value for primary key id on App\Entity\UserContact
In your association, the owning side is User and the inverse side is UserContact. You must use mappedBy for the inverse side instead inversedBy. So your annotation for the $user attribute in User entity must be this:
/**
* #ORM\OneToOne(targetEntity="User", mappedBy="UserContact")
*/
private $user;
https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/unitofwork-associations.html

Doctrine. One to many. How to write annotations?

I have a OneToMany relation between two tables 'user' and 'profil'
(a user has one only profile, and a profile can be asseigned to many users)
I'm getting this error whenever I try to update the schema in doctrine console.
here is my two entities :
<?php
namespace CNAM\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping\ManyToOne;
/**
* user
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class user
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=40)
*/
private $password;
public function __construct()
{
}
/**
* #var boolean
*
* #ORM\Column(name="etat", type="boolean")
*/
private $etat;
/**
* #var profil $profil
*
* #ORMManyToOne(targetEntity="profil", inversedBy="users", cascade={"persist", "merge"})
* #ORMJoinColumns({
* #ORMJoinColumn(name="profil", referencedColumnName="id")
* })
*/
private $profil;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* #param integer $id
* #return user
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Set password
*
* #param string $password
* #return user
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set etat
*
* #param boolean $etat
* #return user
*/
public function setEtat($etat)
{
$this->etat = $etat;
return $this;
}
/**
* Get etat
*
* #return boolean
*/
public function getEtat()
{
return $this->etat;
}
/**
* Get profil
*
* #return integer
*/
public function getProfil()
{
return $this->profil;
}
/**
* Set profil
*
* #param integer $profil
* #return user
*/
public function setProfil($profil)
{
$this->profil = $profil;
return $this;
}
public function getUsername()
{
return $this->id;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
return $user->getId() == $this->getId();
}
}
<?php
namespace CNAM\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\OneToMany;
/**
* profil
*
* #ORM\Table(name="profil")
* #ORM\Entity
*/
class profil
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="libelle", type="string", length=20)
*/
private $libelle;
/**
* #var ArrayCollection $users
*
* #ORMOneToMany(targetEntity="user", mappedBy="profil", cascade={"persist", "remove", "merge"})
*/
private $users;
public function __construct()
{
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set libelle
*
* #param string $libelle
* #return profil
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
return $this;
}
/**
* Get libelle
*
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* Set id
*
* #param integer $id
* #return profil
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
public function __toString() {
return $this->libelle;
}
}
You have syntax mistake.
#ORMManyToOne - this is mistake.
#ORM\ManyToOne(targetEntity="Profil", inversedBy="users")
Above will be correct. And everywhere you use ORM You need to write ORM\something. ORM - is just a namespace, or simply path to the ORM classes in doctrine vendor directory!
Every class name should start with capital letter. It is a wright way! So you should write class User, but not class user!
You didn't show in Profil class, that you have a lot of users to each profil. the users field will be of array collection type (simple array but with useful methods.) So in Profil class in __construct() method:
public function __construct()
{
$this->users = new ArrayCollection();
}
You have One-To-Many, Bidirectional relation.
You can say :
Every (ONE) profile can have a lot of (MANY) users, which use it (One-To-Many)
Every user can use only one exact profile
So try this
// Class Profil
/**
* Bidirectional - One-To-Many (INVERSED SIDE)
* One Profile can have many users, which use it
*
* #var ArrayCollection $users
*
* #ORM\OneToMany(targetEntity="Path-to-your-user-class\Users", mappedBy="profil", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
// Class user
/**
* Bidirectional - One-To-Many (OWNER SIDE)
* One user have only one profile (or profil)
*
* #var Profil $profil
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Profil", inversedBy="users")
* #ORM\JoinColumn(name="profil_id", referencedColumnName="id")
*/
private $profil;

Symfony does not remove Element from ArrayCollection

i want to remove an role from the roles-ArrayCollection in the User Entity.
User and Role have an M:N connection.
In my Controller:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->find($userId);
$user->removeRole($roleID);
$em->flush();
If I execute the controller, there are no error messages.
But the Role is still assigned to the user.
User Entity
namespace Chris\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="usermanagement_users")
* #ORM\Entity(repositoryClass="Chris\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface,\Serializable
{
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
$this->isActive = true;
}
/**
* #inheritDoc
*/
public function getRoles()
{
return $this->roles->toArray();
}
public function setRoles($roles){
$this->roles[] = $roles;
}
public function removeRole($role){
unset($this->roles->toArray()[$role]);
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(type="string", length=60)
*/
private $vorname;
/**
* #ORM\Column(type="string", length=60)
*/
private $nachname;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $letzterLogin;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function setId($id){
$this->id = $id;
}
/**
* #inheritDoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}
Role Entity
<?php
/**
* Created by PhpStorm.
* User: christianschade
* Date: 02.02.15
* Time: 19:29
*/
namespace Chris\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Role
* #ORM\Entity(repositoryClass="Chris\UserBundle\Entity\RoleRepository")
* #ORM\Table(name="usermanagement_roles")
*/
class Role implements RoleInterface {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
public function getRole() {
return $this->role;
}
/**
* #ORM\ManyToMany(targetEntity = "User", inversedBy = "roles")
*
* #var ArrayCollection $users
*/
protected $users;
/**
* #return ArrayCollection
*/
public function getUsers()
{
return $this->users;
}
/**
* #param ArrayCollection $users
*/
public function setUsers($users)
{
$this->users = $users;
}
public function setRoles($roles)
{
$this->role = $roles;
// allows for chaining
return $this;
}
/**
* #inheritDoc
*/
public function getId()
{
return $this->id;
}
/**
* #ORM\ManyToMany(targetEntity = "Chris\UserBundle\Entity\Group", inversedBy = "groups")
*
* #var ArrayCollection $group
*/
private $group;
/**
* #return ArrayCollection
*/
public function getGroup()
{
return $this->group;
}
/**
* #param ArrayCollection $group
*/
public function setGroup($group)
{
$this->group = $group;
}
}
You should use ArrayCollection::removeElement() to remove the role.
public function removeRole($role)
{
$this->roles->removeElement($role);
}
On a side note, I feel your getRoles() implementation is unorthodox as it would be recommended to return the ArrayCollection as is and call toArray() if you need to once you have retrieved it.
public function getRoles()
{
return $this->roles;
}

Symfony: User roles with doctrine: no entities or tables created

I followed the instructions given in the Symfony-Book to get a user-role relation with doctrine updating them in my database.
Symfony - User/Role - Doctrine
But when I update my entities via doctrine:generate:entities, it only generates the existing User.php, but doesn't touch the Role.php. This wouldn't bother me, if the tables in my databse would update with doctrine:schema:update --force. But they don't. The mentioned tables aren't created. In fact, nothing happens. Can you please help me? I am looking forward to any good solution.
My User.php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=24, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="isActive", type="string", length=255, nullable=false)
*/
private $isactive;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=10, nullable=false)
*/
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
private $roles;
public function __construct()
{
$this->isActive = true;
$this->roles = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return $this->roles->toArray();
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isactive
*
* #param string $isactive
* #return User
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return string
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* #var string
*/
private $type;
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
}
Role.php:
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="user_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;
}
}
First tip: give your user table a different name, eg #ORM\Table(name="acme_user").
Second: add in your user class:
/**
* User's roles.
*
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
and in your role class
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
#see: http://symfony.com/doc/2.3/cookbook/security/entity_provider.html

How to insert ProyectosHasCentros table in the entities definition?

I have this three tables in my model:
And I need to create the relationship between them in order to get valid entities but I need some help here. This is what I have right now:
Proyectos.php
<?php
namespace PI\ProyectoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="proyectos")
*/
class Proyectos {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=45, unique=true, nullable=false)
*/
protected $nombre;
/**
* #ORM\Column(type="boolean", nullable=true)
*/
protected $estado;
/**
* #ORM\Column(type="string", length=45, nullable=false)
*/
protected $pais;
/**
* #ORM\ManyToOne(targetEntity="PI\ClienteBundle\Entity\Clientes", cascade={"all"})
* #ORM\JoinColumn(name="cliente", referencedColumnName="id")
*/
protected $clientes;
public function getId() {
return $this->id;
}
public function setNombre($nombre) {
$this->nombre = $nombre;
}
public function getNombre() {
return $this->nombre;
}
public function setEstado($estado) {
$this->estado = $estado;
}
public function getEstado() {
return $this->estado;
}
public function setPais($pais) {
$this->pais = $pais;
}
public function getPais() {
return $this->pais;
}
public function setClientes(\PI\ClienteBundle\Entity\Clientes $clientes) {
$this->clientes = $clientes;
}
public function getClientes() {
return $this->clientes;
}
}
And Centros.php
<?php
namespace PI\CentroBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="centros")
*/
class Centros {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="text", unique=true, nullable=false)
*/
protected $descripcion;
/**
* #ORM\ManyToMany(targetEntity="PI\UnidadBundle\Entity\Unidades", inversedBy="centros", cascade={"persist"})
* #ORM\JoinTable(name="unidades_has_centros",
* joinColumns={#ORM\JoinColumn(name="centros_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="unidades_id", referencedColumnName="id")}
* )
*/
protected $unidades;
public function __construct() {
$this->unidades = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId() {
return $this->id;
}
public function setDescripcion($descripcion) {
$this->descripcion = $descripcion;
}
public function getDescripcion() {
return $this->descripcion;
}
public function setUnidades(\PI\UnidadBundle\Entity\Unidades $unidades) {
$this->unidades[] = $unidades;
}
public function getUnidades() {
return $this->unidades;
}
}
How I add the n:m relationship in both sides to get valid entities and to make CRUD operations more easy than create a new Entity ProyectosHasCentros.php and put fields inside it?
If you don't add proyectos_cliente to the second table you can use the ManyToMany relationships in your entities. If you want extra fields, then you have to create an extra entity which contains the relationships with Proyectos and Centros. Beside the relationships you add extra properties, like proyectos_cliente.
Try to use one PK and use UNIQUE for the cliente field

Resources