8

我将 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()?

4

1 回答 1

21

将此添加到您的 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));
于 2013-05-24T07:52:32.890 回答