我用查询构建器编写了一个查询,但我找不到只返回一个Account实体数组的方法。基本上我在account_packages表上进行查询,但后来我需要返回来自另一个表的帐户entites。是否可以使用一个查询?
public function getAccountsWhichLocationPackagesExpire(DateTime $dateExpire)
{
$qb = $this->entityManager->createQueryBuilder();
$qb->select('p')
->from('ServicePaymentBundle:AccountPackage', 'p')
->where($qb->expr()->eq('p.dateExpire', ':dateExpire'))
->andWhere('p.alias = :alias')
->andWhere('p.enabled = :enabled')
->setParameter('dateExpire', $dateExpire->format('Y-m-d'))
->setParameter('alias', Package::TYPE_LOCATION)
->setParameter('enabled', 1)
->leftJoin('p.account', 'a');
try {
$result = $qb->getQuery()->getResult(); # Here I only need an array of account entities, not account packages. It would be nicer if they were distinct.
# echo count($result);
return $result;
}
catch(NoResultException $e) {
return [];
}
}
答案 0 :(得分:4)
您应该反转您的查询。从Accounts
中选择并加入AccountPackage
。像这样:
$qb->select('a')
->from('ServicePaymentBundle:Account', 'a')
->leftJoin('a.accountPackages', 'p')
->where($qb->expr()->eq('p.dateExpire', ':dateExpire'))
->andWhere('p.alias = :alias')
->andWhere('p.enabled = :enabled')
->setParameter('dateExpire', $dateExpire->format('Y-m-d'))
->setParameter('alias', Package::TYPE_LOCATION)
->setParameter('enabled', 1);
仅当您的关系是双向的时,这才有效。像:
Account
实体中的:
/**
* @ORM\OneToMany(targetEntity="SomePath\AccountPackage", inversedBy="account")
*/
private $accountPackages;
并在AccountPackage
实体中:
/**
* @ORM\ManyToOne(targetEntity="SomePath\Account", inversedBy="accountPackages")
*/
private $account;