Symfony3 QueryBuilder orderBy实体字段

Symfony3 QueryBuilder orderBy entity field

我正在使用 querybuilder 将查询构建为 EntityRepository。我有一个 ManyToOne 关系(通过 ID),我试图通过关系的值对查询进行排序。下面的代码片段。

namespace AppBundle\Entity\Repository;
class ContratoRepository extends EntityRepository
{

    public function getWithoutParams($ops)
    {

        $query=$this->createQueryBuilder('e')
            ->orderBy('e.proc','ASC');
        return $query->getQuery()->getResult();
    }

现在我的实体

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\ContratoRepository")
 */

    class Contrato
    {
...
     /**
         * @ORM\ManyToOne(targetEntity="AppBundle\Entity\ContratosAdmin\Proc")
         * @ORM\JoinColumn(name="id_proc", referencedColumnName="id_proc")
         * @ORM\OrderBy({"name" = "ASC"})
         **/
        private $proc;

现在我的问题是,是否可以通过我的 Proc 实体中的 "name" 字段进行排序?就像现在一样,它是按 Id 排序的。

谢谢, 问候。

根据学说文档应该是可以的: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/ordered-associations.html

但是根据这个你必须稍微调整你的查询,否则 orderBy 注释将不会包含在查询中。

试试这个查询:

public function getWithoutParams($ops)
    {
        $query=$this->createQueryBuilder('e')
               ->select('e, p')
               ->leftJoin('e.proc', 'p');

        return $query->getQuery()->getResult();
    }

根据文档,在这种情况下应该自动添加 orderBy。

对于没有注释的使用,只需加入关系并添加手动 orderBy,就像 Grechka 提到的那样。