Bendy
Bendy

Reputation: 3576

Doctrine one-to-many mappings: How big should the "Many" side be?

I have more experience with SQL databases than I do with Symfony and am hoping someone can clarify the association mappings on how Doctrine connects the database to Symfony.

Taking a one-to-many mapping between Category and Product as an example:

I have very little need to record productIDs as a long string in each category record and I assume that having it is an unnecessary overhead. If I really needed to get a list of all products in a category record in the future though then I assume I could just manually query it still?

By extension, to get the above, I would need a unidirectional many-to-one association. If this is the case though, then would I still (and how would I?) be able to control such things as on delete cascade if required?

Upvotes: 0

Views: 123

Answers (1)

Wilt
Wilt

Reputation: 44364

I think you are not totally understanding how this works in Doctrine. I hope this helps:

If you do a one-to-many between your Category and Product (one category has many products) with doctrine then it means that all you need is a category_id column in your product table (product is in this case the owning side of the relationship). You can make the relationship bi-directional without any consequences for the category table. Doctrine will allow you to get the products for a category easily by doing:

$category->getProducts();

In the background a query will be performed where all products with matching category_id column are resolved from your database and added to the products collection in the Category entity.

Check the example in the docs. It is exactly like yours, but then a one-to-many between product and features.

To prevent all products from loading when querying your category you can mark the inverse side as fetch="EXTRA_LAZY".

If you still have questions after this, just leave a comment.

Update:

So to make it very clear: doctrine does not add a column inside the category table. In your case the products property only exist in the object model not in the database model.

Upvotes: 2

Related Questions