Search code examples
phpdoctrine-orm

What is the difference between inversedBy and mappedBy?


I am developing my application using Zend Framework 2 and Doctrine 2.

While writting annotations, I am unable to understand the difference between mappedBy and inversedBy.

When should I use mappedBy?

When should I use inversedBy?

When should I use neither?

Here is an example:

 /**
 *
 * @ORM\OneToOne(targetEntity="\custMod\Entity\Person", mappedBy="customer")
 * @ORM\JoinColumn(name="personID", referencedColumnName="id")
 */
protected $person;

/**
 *
 * @ORM\OneToOne(targetEntity="\Auth\Entity\User")
 * @ORM\JoinColumn(name="userID", referencedColumnName="id")
 */
protected $user;

/**
 *
 * @ORM\ManyToOne (targetEntity="\custMod\Entity\Company", inversedBy="customer")
 * @ORM\JoinColumn (name="companyID", referencedColumnName="id")
 */
protected $company;

I did a quick search and found the following, but I am still confused:


Solution

    • mappedBy has to be specified on the inversed side of a (bidirectional) association
    • inversedBy has to be specified on the owning side of a (bidirectional) association

    from doctrine documentation:

    • ManyToOne is always the owning side of a bidirectional assocation.
    • OneToMany is always the inverse side of a bidirectional assocation.
    • The owning side of a OneToOne assocation is the entity with the table containing the foreign key.

    See https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/unitofwork-associations.html