I am new to Symfony and Doctrine.
I have an entity "User" and an entity "Type". One user can have one favorite type and one type can have many users that have that specific type as favorite. So I need a Many (User) to One (Type) relationship.
I implemented it and it works fine (mostly). But there is one thing I don't understand.
If I do something like that it works:
$user = new User();
$type = new Type();
$user->setFavoriteType($type);
$em->persist($user);
$em->persist($type);
$em->flush();
The objects are generated and stored to the DB. And the favorite_type_id is correctly set. So changing the owning side works as expected.
But if I add the User to the inverse side (only) and flush the entity manager the favorite_type_id is not set.
$user = new User();
$type = new Type();
$type->getUsers()->add($user); //same with $type->addUser($user);
$em->persist($user);
$em->persist($type);
$em->flush();
Why is that? Is there a reason why it does not work from the inverse side? Do I really have to set this manually? If I manipulate the addUser method in the type entity like "$user->setFavoriteType($this)" it works. But should that not be the task of doctrine?
The documentation says
When a bidirectional association is updated, Doctrine only checks on one of both sides for these changes. This is called the owning side of the association.
So it seems to be the wanted behaviour, is that right? But why? Due to performance? Semantic reasons?
I'd be glad if someone could explain that to me or tell me what I'm doing wrong.
This ManyToOne mapping is required. It tells Doctrine to use the category_id column on the product table to relate each record in that table with a record in the category table.
The owning side is always where the ManyToOne mapping is set (for a ManyToMany relation, you can choose which side is the owning side). Does this means it's not possible to call $category->addProduct () or $category->removeProduct () to update the database?
To update a relationship in the database, you must set the relationship on the owning side. The owning side is always where the ManyToOne mapping is set (for a ManyToMany relation, you can choose which side is the owning side).
Otherwise, you likely need a ManyToOne. There is also a OneToOne relationship (e.g. one User has one Profile and vice versa). In practice, using this is similar to ManyToOne. Suppose that each product in your application belongs to exactly one category.
Check out the Doctrine documentation on cascading.. This should help you get started with what it looks like you want to do, quickly and easily, by adding cascade={"persist"}
and clearing your cache (to rebuild Doctrine's metadata cache).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With