php – 如何使用Doctrine QueryBuilder选择所有列?

我有实体商店,所有者和城镇,我想要计算所有者拥有的所有商店,按城镇分类.

我的控制器中有这个查询

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

您想获得用户和城镇的所有商店吗?
没问题 ! Collection :: filter()是你的朋友!

$storesForAUserAndAGivenTown = $user->getStores()->filter(function (Store $store) use ($town) {
    return ($store->getTown() === $town);
});

而已.

考虑Doctrine的第一个规则是忘记数据库!所以只使用DQL或QueryBuilder,并且只在必要时使用.

希望它会对你有所帮助.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...