php – 如何使用Doctrine QueryBuilder选择所有列?
发布时间:2020-12-13 16:04:42 所属栏目:PHP教程 来源:网络整理
导读:我有实体商店,所有者和城镇,我想要计算所有者拥有的所有商店,按城镇分类. 我的控制器中有这个查询 $query = $this-getDoctrine()-getRepository('WebBundle:Store') -createQueryBuilder('s') -select('t.name,COUNT(s) as counter') -groupBy('s.town') -le
|
我有实体商店,所有者和城镇,我想要计算所有者拥有的所有商店,按城镇分类.
我的控制器中有这个查询 $query = $this->getDoctrine()->getRepository('WebBundle:Store')
->createQueryBuilder('s')
->select('t.name,COUNT(s) as counter')
->groupBy('s.town')
->leftJoin('s.owner','o')
->leftJoin('s.town','t')
->where('s.owner = :id')
->orderBy('t.name','ASC')
->setParameter('id',$id)
->getQuery();
$list = $query->getResult();
有没有办法从Town选择所有列而不是声明每一列?类似于 – >选择(‘t.*,COUNT(s)作为计数器’).我可以选择我现在需要的,但对于较大的表我将需要其他方法. 我试过 – >选择(‘t,COUNT(s)作为计数器’)但我收到了异常错误. 有关详细信息,在我的twig模板中,我想显示: {% for town in list %}
<span>{{ town.name }}</b> [{{ town.counter }}]</span>
{% endfor %}
感谢大家的建议! 解决方法
我想你的实体中有一些关系.
所有者必须与商店有1-n的关系. 因此,您的所有者实体将如下所示: class Owner
{
protected $stores;
// ...
public function __construct()
{
$this->stores = new ArrayCollection();
}
public function getStores()
{
return $this->stores;
}
public function setStores($stores)
{
$this->stores = new ArrayCollection();
foreach ($stores as $store)
{
$this->stores->add($store);
}
return $this;
}
public function addStore(Store $store) // ... can use $this->store->add()
public function removeStore(Store $store) // ... can use $this->store->removeElement()
// etc ...
}
所以现在,您可以使用Collection :: count()Doctrine方法! $storesCnt = $user->getStores()->count(); 您想获得用户和城镇的所有商店吗? $storesForAUserAndAGivenTown = $user->getStores()->filter(function (Store $store) use ($town) {
return ($store->getTown() === $town);
});
而已. 考虑Doctrine的第一个规则是忘记数据库!所以只使用DQL或QueryBuilder,并且只在必要时使用. 希望它会对你有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
