使用Doctrine仅从ManyToMany获取ID的列表 [英] Get only list of ID's from ManyToMany with Doctrine

查看:160
本文介绍了使用Doctrine仅从ManyToMany获取ID的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ManyToMany关联字段,并且我只想获取所有ID而又不对该字段中的任何子实体进行水化处理.

I have a ManyToMany associated field, and I'm in a situation where I'm only trying to get all the ID's without hydrating any of the sub-entities in the field.

我知道在我访问该字段时将有一个查询来查询实体引用,这很好/很正常.但是我需要遍历ID,但是我不知道如何在不进行操作的情况下获取

I understand there will be a query to aquire the entity references the moment I access the field, and that's fine/expected. But I need to loop through the ID's, but I don't quite know how to get them without doing

$ids = [];
foreach($mainEntity->getSubEntities() as $subentity) {
   $ids[] = $subentity->getId();
}

由于foreach循环,这似乎也自动使子实体水合.这会导致大量不必要的查询,并影响页面加载时间.

This also seems to hydrate the sub entity automatically, im assuming because of the foreach loop. This results in a lot of unnecessary queries and impacts page load time.

我也将子实体字段标记为EXTRALAZY.

I have the subentity field marked with EXTRALAZY as well.

/**
 * @var ArrayCollection
 * @ORM\ManyToMany(targetEntity="User", fetch="EXTRA_LAZY")
 * @ORM\JoinTable(name="user_friends")
 */
protected $friends;

推荐答案

由于getKeys()仅返回PersistentCollection的顺序索引,我发现此oneliner作为解决方案:

As getKeys() returns only the sequential indexes of a PersistentCollection, I found this oneliner as a solution:

$myCollectionIds = $myCollection->map(function($obj){return $obj->getId();})->getValues();

IN上下文中可以流畅地工作.

Works smoothly in IN contexts.

这篇关于使用Doctrine仅从ManyToMany获取ID的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆