I have two entities: User and Company and the relationship between them is n:m. In my User.php
entity I have this code:
/**
* @ORM\ManyToMany(targetEntity="PL\CompanyBundle\Entity\Company", mappedBy="users", cascade={"all"})
*/
protected $companies;
public function __construct() {
$this->companies = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setCompanies(\PL\CompanyBundle\Entity\Company $companies) {
$this->companies = $companies;
}
public function getCompanies() {
return $this->companies;
}
And in my Company.php
entity I have this other code:
/**
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User", mappedBy="companies")
*/
protected $users;
public function __construct() {
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
But I got this error:
ContextErrorException: Notice: Undefined index: inverseJoinColumns in /var/www/html/apps/portal_de_logistica/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1041
What is wrong in the mapping?
EDIT Refactor code
Following instructions from @ahmed-siouani I made the following changes:
User.php
/**
* @ORM\ManyToMany(targetEntity="PL\CompanyBundle\Entity\Company", inversedBy="users")
* @ORM\JoinTable(name="fos_user_user_has_company",
* JoinColumns={@ORM\JoinColumn(name="fos_user_user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="company_id", referencedColumnName="id")}
* )
*/
protected $companies;
where fos_user_user_has_company
is the table added for the n:m
relationship.
Company.php
/**
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User", mappedBy="companies")
*/
protected $users;
And now the error is:
AnnotationException: [Creation Error] The annotation @ORM\JoinTable declared on property Application\Sonata\UserBundle\Entity\User::$companies does not have a property named "JoinColumns". Available properties: name, schema, joinColumns, inverseJoinColumns
Any?
In addition to @Ahmed solution take care of typos since I made one and for that the second error I got. See my annotation said:
But right one is:
Differences are in this line:
You may need to specify the
joinColumns
and theinverseJoinColumns
when defining thejoinTable
. For a bidirectional many-to-many definition is would be something like,While your Company class should be defined as follow,
My fault was that both sides of the ManyToMany had been defined with mappedBy, but only one side should have been using mappedBy and the other side should have used inversedBy (this is normally defined at main entity, that controls the collection).