我想在Doctrine 2中创建这个语句:
SELECT Id, ParentId , LastName
FROM Customer
WHERE ParentId IN
(SELECT Id
FROM Customer
WHERE ParentId IN $id)
)
这是我的代码:
public function findByCustomer($id) : array
{
$qb = $this->_em->createQueryBuilder();
$qb1 = $this->_em->createQueryBuilder();
$qb->select('Customer.Id , Customer.ParentId , Customer.LastName ');
$qb->from('..\City\Model\Entities\Customer', 'Customer');
$qb->add('where', $qb->expr()->in('Customer.ParentId',
$qb1->select('Customer.Id');
$qb1->from('..\City\Model\Entities\Customer', 'Customer');
$qb1->add('where', $qb->expr()->in('Customer.ParentId', $id)
$qb1 = $qb1->getQuery();
return $qb1->getResult();
)
);
$qb = $qb->getQuery();
return $qb->getResult();
}
但它根本不起作用。有什么建议吗?
答案 0 :(得分:2)
您可以通过querybuilder这样查看子查询:
$subQuery = $this->_em->createQueryBuilder();
$subQuery->select('c1.Id');
$subQuery->from('..\City\Model\Entities\Customer', 'c1');
$subQuery->add('where', $qb->expr()->in('c1.ParentId', $id)
$qb = $this->_em->createQueryBuilder();
$qb->select('Customer.Id , Customer.ParentId , Customer.LastName ');
$qb->from('..\City\Model\Entities\Customer', 'Customer');
$qb->andWhere($qb->expr()->in('Customer.ParentId', $subQuery->getDQL()) );
$query = $qb->getQuery();
return $query->getResult();
希望这个帮助
答案 1 :(得分:0)
我有更好的方式来执行此查询,我希望这会对您有所帮助。
您可以在doctrine2
中使用直接sql语句,如下所示
$sql = "SELECT Id, ParentId , LastName
FROM Customer
WHERE ParentId IN
(SELECT Id
FROM Customer
WHERE ParentId IN $id)
)";
$data = $this->doctrine->sql_conn->fetchAll($sql , array());
我总是使用这个在doctrine2
中编写复杂的sql语句。我希望这会对你有所帮助