当插入具有关联的实体时,有没有办法只使用FK而不是检索实体? [英] 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.
如果我已经拥有关联实体的FK,有没有办法将主实体插入到db只有FK的填充?
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?
或者我一直都要
- 通过FK检索关联的实体,
- 填充主体实体的属性,参考协议,
- ,然后调用persist方法。 >
- retrieve the associated entities via the FK's,
- populate the primary entity's properties referring to the assocations,
- and then invoke the persist method.
推荐答案
你想要一个参考代理
说我有帖子和标签。一个帖子有很多标签。我从用户那里得到一堆标签,他们检查了一堆复选框。
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.
以下内容将添加标签到现有的帖子,而不是首先获取每个标签实体。它通过使用由 EntityManager :: getReference()
生成的引用代理来实现:
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();
这篇关于当插入具有关联的实体时,有没有办法只使用FK而不是检索实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!