Symfony,即使FK为空,也可以通过外键排序

Symfony,即使FK为空,也可以通过外键排序,symfony,doctrine-orm,Symfony,Doctrine Orm,假设我有一个这样的实体 <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * * @ORM\Table(name="entity") * @ORM\Entity(repositoryClass="AppBundle\Repository\ MyEntityRepository") */ class Entity { /** * @ORM\Column(name="id

假设我有一个这样的实体

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 * @ORM\Table(name="entity")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ MyEntityRepository")
 */
class Entity
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Kind")
     */
    private $kind;
}

您正在使用内部联接。这是一个更有效的查询,因为它只检索两个表之间匹配的记录

如果要获取空值,需要使用
leftJoin
。这应该小心使用,因为这些查询比
innerJoin
更重,因为考虑的是基表中的所有记录,而不仅仅是匹配项

<?php

namespace AppBundle\Repository;

class MyEntityRepository extends \Doctrine\ORM\EntityRepository
{
    public function getAllOrdered()
    {
        return $this->createQueryBuilder('e')
            ->leftJoin('e.kind', 'k')
            ->orderBy('k.id', 'ASC')
            ->getQuery()
            ->getResult(); 
    }
}

改用
leftJoin
。of
join
join/internal join
将排除不存在的记录。
<?php

namespace AppBundle\Repository;

class MyEntityRepository extends \Doctrine\ORM\EntityRepository
{
    public function getAllOrdered()
    {
        return $this->createQueryBuilder('e')
            ->leftJoin('e.kind', 'k')
            ->orderBy('k.id', 'ASC')
            ->getQuery()
            ->getResult(); 
    }
}