Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

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

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.
question from:https://stackoverflow.com/questions/5382170/when-inserting-an-entity-with-associations-is-there-a-way-to-just-use-the-fk-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...