Having a hard time wrapping my head around this one. I have a Page entity and a Keyword entity. I’ve created a member variable called $keywords in my Page entity that has a ManyToMany association that creates a join table called “pages_keywords”. In my application, I want to give the ability to add a keyword to a page. How would I go about adding that record to the database?
I can access the Page entity’s $keywords member variable but I’m not sure where to go from there. I see that the Doctrine implementation of ArrayCollection has an add() method that just takes a value. Can I just pass it the Keyword entity’s id and will that create the record for me?
Assuming you know the primary key value of the entity you are looking to associate it with (in your example, the $keywordId), the best way to do this is to get a reference to the entity. This gets you a reference without doing a database lookup for the associated entity.
The solution you posted in your follow-up answer has the disadvantage of requiring an extra trip to the database to retrieve the keyword record. Retrieving it as a reference means that there is no extra database lookup: