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

标签 php mysql symfony doctrine-orm doctrine

我有实体 StoreOwnerTown,我想计算所有商店所有者有,按他们的城镇分类。

我的 Controller 中有这个查询

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

有什么方法可以从城镇中选择所有列而不是声明每一列?类似于 ->select('.*, COUNT(s) as counter')。我现在可以选择我需要的那些,但对于更大的表,我将需要其他方法。

我试过 ->select('t, COUNT(s) as counter') 但我遇到异常错误。

有关更多信息,我想在我的 Twig 模板中显示:

{% for town in list %}
    <span>{{ town.name }}</b> [{{ town.counter }}]</span>
{% endfor %}

感谢大家的建议!

最佳答案

我猜你在你的实体中有一些关系。

Owner 必须与 Store 具有 1-n 关系。

因此,您的 Owner 实体将如下所示:

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() 是你的 friend !

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

就是这样。

考虑 Doctrine 的第一条规则是忘记数据库!,所以仅在必要时才使用 DQL 或 QueryBuilder。

希望对你有所帮助。

关于php - 如何使用 Doctrine QueryBuilder 选择所有列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37282862/

相关文章:

php - PHP 中的 MySQL 错误,但不是通过 CLI

php - 开发强大的应用程序

php - mysql 使用 IF NOT IN 关键字或替代方法选择所有其他数据

javascript - ajax - 验证数据库中是否已存在行

Python mySQL - 转义引号

php - 如何在保存数据之前在输入表单上运行脚本

mysql - Ruby on Rails 服务器连接错误

php - Doctrine 2,HINT_FORCE_PARTIAL_LOAD 不会获取连接的实体

php - 如何将 Symfony2 路由转储到 nginx?

php - Symfony 身份验证(您不能从 EntityUserProvider 刷新用户)