我尝试与doctrine查询构建器进行连接。
$query = $this->createQueryBuilder('od');
$query->innerJoin(Order::class, 'o', Expr\Join::WITH, 'o.orderid = od.orderid');
$query->where('o.userid = :userid')
$query->andWhere('od.orderstatusid IN (:orderstatusid)')
$query->setParameter('userid', $userid);
$query->setParameter('orderstatusid', array(5, 6, 7, 8, 10))
请求失败,因为生成SQL是:
SELECT od FROM OrderDetail od INNER JOIN Order o WITH o.orderid = od.orderid WHERE o.userid = :userid AND od.orderstatusid IN (:orderstatusid)
或者它应该是
SELECT od FROM OrderDetail od INNER JOIN Order o ON o.orderid = od.orderid WHERE o.userid = :userid AND od.orderstatusid IN (:orderstatusid)
我无法使用$ query-> innerJoin(Order :: class,' o',Expr \ Join :: ON,' o.orderid = od.orderid');因为我收到了这个错误:
[Syntax Error] line 0, col 91: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_WITH, got 'ON'
如果我不使用连接条件,则学说不会从模型中获取它,所以我没有得到好的结果。
如何使用querybuilder进行连接和哪里?
感谢您的帮助
编辑: 这是模型:
OrderDetail:
type: entity
table: order_detail
repositoryClass: OrderDetailRepository
id:
orderdetailid:
type: integer
nullable: false
options:
unsigned: false
id: true
fields:
...
lifecycleCallbacks: { }
manyToOne:
order:
targetEntity: Order
inversedBy: orderdetails
joinColumn:
name: orderid
referencedColumnName: orderid
Order:
type: entity
table: order
id:
orderid:
type: integer
nullable: false
options:
unsigned: false
id: true
fields:
lifecycleCallbacks: { }
oneToMany:
orderdetails:
targetEntity: OrderDetail
mappedBy: order
fetch: EAGER
答案 0 :(得分:1)
签出您的实体后,我认为您的查询可以简化一下。实际上你根本不需要WITH。
$result = $this->createQueryBuilder('od')
->join('od.order', 'o')
->addSelect('o')
->where('o.userid = :userid')
->andWhere('od.orderstatusid IN (:orderstatusid)')
->setParameter('userid', $userid)
->setParameter('orderstatusid', array(5, 6, 7, 8, 10))
->getQuery()->getResult()
;
Doctrine很聪明,知道od.order表示OrderDetail - >订购关系并管理您的加入。当你有一些非常具体的查询要求时,你真的只需要使用WITH。
答案 1 :(得分:0)
在Doctrine文档中解释:
$qb->innerJoin('u.Group', 'g', Expr\Join::WITH, $qb->expr()->eq('u.status_id', '?1'));
OR
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1');
OR
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1', 'g.id');
我建议使用这种方式:
$query->innerJoin('od.Order', 'o', 'WITH', 'od.orderstatusid IN (:orderstatusid)');
这种方式查询是最优化的,不需要使用" o.orderid = od.orderid"和" $ query-> andWhere(' od.orderstatusid IN(:orderstatusid)')"。