gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:22:39 26 4
gpt4 key购买 nike

我将 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;
}

现在在我的 Controller 中,我需要执行以下操作:
    $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() 吗?

最佳答案

将此添加到您的 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));

关于symfony - Doctrine2 findBy() 按连接表字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16729957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com