当有on或condition时,我有左连接的本机sql查询,如何在查询构建器中表示它?
$query = " SELECT te.id
FROM task_executions AS te
INNER JOIN tasks AS t ON t.id = te.task_id
LEFT JOIN cost_objects AS co ON co.id = t.cost_object_id
LEFT JOIN cost_object_managers AS com ON com.cost_object_id = co.id OR com.cost_object_id = co.parent_id
我需要在查询构建器中表示它,但在User
实体中我有ManyToMany关系,没有单独的表,当我尝试使用条件左连接时我有错误SingleValuedAssociationField expected.
用户实体
class User
{
...
/**
* @ORM\ManyToMany(targetEntity="CostObject", mappedBy="users")
*/
private $costObjects;
}
CostObject实体
class CostObject
{
/**
* @var CostObject
*
* @ORM\ManyToOne(targetEntity="CostObject", inversedBy="children")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
* })
*/
private $parent;
/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="User", inversedBy="costObjects")
* @ORM\JoinTable(name="cost_object_managers",
* joinColumns={@ORM\JoinColumn(name="cost_object_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
private $users;
我的查询构建器没有条件
$qb->select('te')
->from('AppBundle:TaskExecution', 'te')
->innerJoin('te.task', 't')
->leftJoin('t.costObject', 'co')
->leftJoin('co.users', 'com')
这是$query->getSQL()
SELECT some_name FROM task_executions t0_ INNER JOIN tasks t1_ ON t0_.task_id = t1_.id LEFT JOIN cost_objects c2_ ON t1_.cost_object_id = c2_.id LEFT JOIN cost_object_managers c4_ ON c2_.id = c4_.cost_object_id LEFT JOIN users u3_ ON u3_.id = c4_.user_id ORDER BY t0_.execution_start DESC
我需要像在nativbe查询中一样进行更改,但是当我向左连接添加条件时,我会收到错误
查询条件
$qb->select('te')
->from('AppBundle:TaskExecution', 'te')
->innerJoin('te.task', 't')
->leftJoin('t.costObject', 'co')
->leftJoin(
'co.users',
'com',
Join::WITH,
$qb->expr()->orX
(
'com.costObjects = co.id',
'com.costObjects = co.parent'
)
)
和错误
[Semantical Error] line 0, col 121 near 'costObjects =': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
我尝试在回答
中添加IDENTITY
->leftJoin('t.costObject', 'co')
->leftJoin(
'co.users',
'com',
Join::WITH,
$qb->expr()->orX
(
'IDENTITY(com.costObjects) = co.id',
'IDENTITY(com.costObjects) = co.parent'
)
)
但仍有错误
[Semantical Error] line 0, col 130 near 'costObjects)': Error: Invalid PathExpression. Must be a SingleValuedAssociationField.
答案 0 :(得分:1)
试试这个:
$qb->select('te')
->from('AppBundle:TaskExecution', 'te')
->innerJoin('te.task', 't')
->leftJoin('t.costObject', 'co')
->leftJoin(
'co.users',
'com',
Join::WITH,
$qb->expr()->orX
(
'IDENTITY(com.costObjects) = co.id',
'IDENTITY(com.costObjects) = co.parent'
)
)