问题描述
我有与申请人有关的实体申请
/**
* @ORM\ManyToOne(targetEntity=Applicant::class,inversedBy="applications")
* @ORM\JoinColumn(nullable=false)
*/
private $applicant;
现在我尝试通过我拥有的ApplicantRepository中的申请人名称为搜索应用程序创建QueryBuilder
public function searchByName($searchString)
{
return $this->createqueryBuilder('a')
->andWhere('a.name LIKE :phrase')->setParameter('phrase','%'.$searchString.'%')
->getQuery()
->getResult();
}
在我拥有的控制器中
$applicants = $applicantRepository->searchByName($searchString);
现在,我要在此申请人集合中搜索具有申请人名称的申请。我可以使用QueryBuilder吗?
我正在尝试类似的事情
public function getApprovedSearchByApplicants($applicants)
{
return $this->createqueryBuilder('a')
->andWhere('a.applicant IN (:applicants)')
->setParameter('applicants',$applicants)
->getQuery()
->getResult();
}
解决方法
因此,查看您的配置,您的Application::$applicant
=== Applicant::$name
,因为默认情况下Application::$applicant
属性的值为Applicant::$id
。您可以检查documentation。
所以,这样,您需要像这样制作:
/**
* @ORM\ManyToOne(targetEntity=Applicant::class,inversedBy="applications")
* @ORM\JoinColumn(name="applicant_name",referencedColumnName="name",nullable=false)
*/
private $applicant;
应该可以。
问题更新和讨论后的更新:
因此,问题出在数据库中的测试数据中。不好的问题。
,通过搜索字符串搜索:
$entityManager
->createQuery('
SELECT ct
FROM App\Entity\Application ct
JOIN ct.applicant nt
WHERE nt.name LIKE :phrase
')
->setParameters(['phrase' => "%$searchString%"]
->getResult();
按申请人搜索:
$entityManager
->createQuery('
SELECT ct
FROM App\Entity\Application ct
JOIN ct.applicant nt
WHERE nt IN (:nts)
')
->setParameters(['nts' => $applicants]
->getResult();
,
我没有测试它,但是类似下面的代码应该可以解决问题。该解决方案与goulashsoup提出的解决方案几乎相同,但是没有键入原始DQL。
/**
* @param array|Applicant[] $applicants
*
* @return array|Application[]
*/
public function findByApplicants(array $applicants): array
{
$qb = $this->createQueryBuilder('a')
return $qb->innerJoin('a.applicant','at')
->where(
$qb->expr()->in('at.id',':applicants')
)
->setParameter('applicants',$applicants)
->getQuery()
->getResult();
}
我认为您不需要使用“ ApprovedSearch”命名该函数,因为该方法仅知道您想要其应用程序列表的申请人列表。