Reputation: 1047
Please, could anybody explain with examples idea of “owning side” and “inverse side” concepts in Doctrine? I understand that they are necessary to organize bidirectional relationship, but I can’t realize following text from Doctrine documentation (link):
There are 2 references on each side of the association and these 2 references both represent the same association but can change independently of one another.
Edit
For example, I have entities Customer (owning side) and Company (inverse side). At first, I do following:
$customer = new Customer();
$company = new Company();
$customer->setCompany($company);
$company->setCustomer($customer);
Then I can have two scenarios:
Scenario 1
$company->getCustomer()->setName(‘John’);
$entityManager->persist($company);
$entityManager->flush();
Scenario 2
$customer->getCompany()->setLicenseNumber(‘24535’);
$entityManager->persist($company);
$entityManager->flush();
Do I understand rightly, that in first case association will be persisted correctly, because owning side (through getCustomer()) is changed, but in second case it will be ignored, because owning side is not changed?
Upvotes: 1
Views: 1220
Reputation: 44316
I tried to add quotes from the documentation to my answer. Please leave a comment if you/someone does not agree with my answer or if you see a possibility to improve the explanations...
Example for your Company
and User
...
Customer
entity:
class Customer
{
// ...
/** ONE-TO-ONE BIDIRECTIONAL, OWNING SIDE
* @ORM\OneToOne(targetEntity="Company", inversedBy="customer")
* @ORM\JoinColumn(name="company_id", referencedColumnName="id")
*/
private $company;
// ...
/**
* Set company method
*
* @param Company $company
*/
public function setCompany( Company $company )
{
$this->company = $company;
$company->setCustomer( $this );
}
}
Company
entity:
class Company
{
// ...
/** ONE-TO-ONE BIDIRECTIONAL, INVERSE SIDE
* @OneToOne(targetEntity="Customer", mappedBy="company")
*/
private $customer;
// ...
}
An example:
$company= $em->find('Application\Entity\Company', 1);
$customer = $em->find('Application\Entity\Customer', 1);
$customer->setCompany($company);
$em->persist($customer);
$em->flush();
If you now do $customer = $company->getCustomer();
you will get a Customer
with id 1.
And now imagine not having the line $company->setCustomer( $this );
in the setCompany
method. If you then do $customer = $company->getCustomer();
after setting $company
you will not get a Customer
with id 1. In other words the association on inverse side does not correspond with your database model and does not correspond with the reference on the owning side.
Upvotes: 1