symfony2 querybuilder orderby count manytomany

时间:2013-07-23 11:32:29

标签: symfony sql-order-by createquery

我有一个名为School的实体,它有一个ManyToMany关系“方法”

class School{
 /**
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * @ORM\Column(type="integer")
 */
protected $id;

/**
 * @ORM\ManyToMany(targetEntity="Method", inversedBy="schools")
 * @ORM\JoinTable(name="lk_access_method")
 * @ORM\OrderBy({"name" = "asc"})
 */
protected $methods;
}

现在我想编写一个通过de count“methods”命令的createQueryBuilder

类似的东西:

$schools = $this->createQueryBuilder('s')
            ->select("s")
            ->orderBy("COUNT(s.methods)")
            ->addOrderBy("s.name")
            ->setMaxResults($count)
            ->setFirstResult($pos)
            ->getQuery()
            ->getResult();

但那不起作用......任何人都有更好的主意吗?

1 个答案:

答案 0 :(得分:12)

尝试添加联接

->join('s.methods', 'm')
->orderBy("COUNT(m.id)")

修改

->addSelect('COUNT(m.id) as nMethods')
->join('s.methods', 'm')
->groupBy('s.id')
->orderBy("nMethods", 'DESC')