Doctrine2 findBy()按连接表字段排序

时间:2013-05-24 07:39:33

标签: symfony doctrine-orm

我将Symfony2与Doctrine2一起使用。有以下实体:

/**
 * Person
 *
 * @ORM\Entity(repositoryClass="Acme\Bundle\ConsysBundle\Entity\PersonRepository")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="person")
 */
class Person
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * 
     * @ORM\ManyToOne(targetEntity="Company", inversedBy="persons", fetch="EAGER")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id", onDelete="SET NULL")
     */
    private $company;

}

/**
 * Company
 *
 * @ORM\Entity(repositoryClass="Acme\Bundle\ConsysBundle\Entity\CompanyRepository")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="company")
 */
class Company
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     */
    private $name;
}

现在我的控制器中需要执行以下操作:

    $repository = $this->getDoctrine()->getRepository('AcmeConsysBundle:Person');
    $people = $repository->findBy(
            array(),
            // here I want to order by the company name
            // that is taken from the Company entity
            array('company.name' => 'asc') 
    );

这段代码当然行不通,说“company.name”无法识别。但那我该如何通过该专栏订购呢?是否可以使用findBy()?

1 个答案:

答案 0 :(得分:16)

将此添加到您的PersonRepository

public function findAllOrderByCompany()
{
    return $this->createQueryBuilder('p')
        ->leftJoin('p.company','c')
        ->orderBy('c.name', 'asc')
        ->getQuery() 
        ->getResult();
}

如果要按Company :: getName

对Person实体的现有集合进行排序
$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getCompany()->getName() < $b->getCompany()->getName()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));