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



让我们想象一下我有一个像这样的实体

<?php
namespace AppBundleEntity;
use DoctrineORMMapping as ORM;
/**
*
* @ORMTable(name="entity")
* @ORMEntity(repositoryClass="AppBundleRepository MyEntityRepository")
*/
class Entity
{
/**
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORMColumn(name="title", type="string", length=255)
*/
private $title;
/**
* @ORMManyToOne(targetEntity="AppBundleEntityKind")
*/
private $kind;
}

我想查询它们并按种类订购。以下是我在存储库中所做的操作

<?php
namespace AppBundleRepository;
class MyEntityRepository extends DoctrineORMEntityRepository
{
public function getAllOrdered()
{
return $this->createQueryBuilder('e')
->join('e.kind', 'k')
->orderBy('k.id', 'ASC')
->getQuery()
->getResult(); 
}
}

这很好,但完全忽略了所有类型为null的行。

那么,即使种类为null,我如何检索和排序所有实体呢?

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

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

<?php
namespace AppBundleRepository;
class MyEntityRepository extends DoctrineORMEntityRepository
{
public function getAllOrdered()
{
return $this->createQueryBuilder('e')
->leftJoin('e.kind', 'k')
->orderBy('k.id', 'ASC')
->getQuery()
->getResult(); 
}
}

最新更新