我有实体 Store、Owner 和 Town,我想计算所有商店所有者有,按他们的城镇分类。
我的 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/