Doctrine2中是否有任何方法可以通过复合主键数组找到实体包?
$primaryKeys = [
['key1'=>'val11', 'key2'=>'val21'],
['key1'=>'val12', 'key2'=>'val22']
];
答案 0 :(得分:1)
您必须将自定义方法添加到存储库。例如:
$repository = $em->getRepository('Application\Entity\Class');
$repository->findByPrimaryKeys();
在您的Application\Entity\Class
存储库中:
/**
* Find entity by primary keys.
*
* @param Parameters[] $array
* @return Paginator
*/
public function findByPrimaryKeys(array $array)
{
$qb = $this->createQueryBuilder('e');
foreach($array as $index => $keys){
$key1 = $index * 2 + 1;
$key2 = $index * 2 + 2;
$qb->orWhere(
$qb->expr()->andX(
$qb->expr()->eq('e.key1', '?'.$key1),
$qb->expr()->eq('e.key2', '?'.$key2)
)
);
$qb->setParameter($key1, $keys['key1']);
$qb->setParameter($key2, $keys['key2']);
};
return $qb->getQuery()->getResult();
}
也许还有其他方法,但这有效并导致遵循DQL查询:
SELECT e FROM Application\Entity\Class e WHERE
(e.key1= ?1 AND e.key2= ?2)
OR
(e.key1= ?3 AND e.key2 = ?4)