When inserting an entity with associations, is the

2020-02-07 16:06发布

I need to insert an entity which has associations.

If I already have the FK's of the associated entities, is there a way to insert the primary entity into the db with just the FK's populated?

Or do I always have to

  • retrieve the associated entities via the FK's,
  • populate the primary entity's properties referring to the assocations,
  • and then invoke the persist method.

4条回答
我只想做你的唯一
2楼-- · 2020-02-07 16:32

In regards to using a reference proxy
In my investigations this is only partly a solution, as follows:

Yes, you do not have to pro-actively retrieve the related record (because you create a proxy record), but when you flush (commit) the update transaction it still first executes a select statement to retrieve the related record, and then only does the update (all in one hit to the db).
This is inefficient and should not be necessary (we have the foreign-key id, why retrieve the record..?)

So while not a complete solution, what you do gain is only a single connection to the database (which is good) and slightly simplified code.

I am not sure if there is a solution to this at the moment...??
Hopefully the doctrine bods will update in the future and if using the proxy logic we should gain an automatic performance enhancement...

查看更多
家丑人穷心不美
3楼-- · 2020-02-07 16:45

You should retrieve the entity to be related and the make the relationship.

I assume you could manually specify the relationship by directly accessing the database through the DBAL layer but I wouldn't not recommend this, nor have I tried it.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-07 16:52

You want a reference proxy

Let's say I have Posts and Tags. A Post hasMany Tags. I get a bunch of tags from the user, who checked a bunch of checkboxes.

The following would add tags to an existing post, without fetching each tag entity first. It does this by using reference proxies, generated by EntityManager::getReference():

$tag_ids = $_POST['tag_id']; // an array of integers representing tag IDs.
$post = $em->getRepository('Post')->find($post_id); // returns a Post entity.

foreach($tags_ids as $tid){
   $post->addTag($em->getReference('Tag',$tid));
}
$em->persist($post);
$em->flush();
查看更多
唯我独甜
5楼-- · 2020-02-07 16:56

You can do this using entityManager::merge

$post = new Post();
$post->setPostCategory(['id' => 1]);
$em->persist($em->merge($post));
$em->flush();
查看更多
登录 后发表回答