When inserting an entity with associations, is there a way to just use the FK instead of retrieving the entity?

后端 未结 4 467
忘掉有多难
忘掉有多难 2020-12-12 19:28

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 wi

4条回答
  •  猫巷女王i
    2020-12-12 20:00

    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();
    

提交回复
热议问题