When inserting an entity with associations, is there a way to just use the FK instead of retrieving the entity?(插入具有关联的实体时,有没有办法只使用 FK 而不是检索实体?)
问题描述
我需要插入一个具有关联的实体.
I need to insert an entity which has associations.
如果我已经拥有关联实体的 FK,有没有办法将主要实体插入到仅填充 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方法.
推荐答案
你想要一个 引用代理
假设我有帖子和标签.一个帖子有很多标签.我从用户那里得到了一堆标签,他们检查了一堆复选框.
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 而不是检索实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:插入具有关联的实体时,有没有办法只使用 FK 而不是检索实体?


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01