如何使用DQL创建多个连接

时间:2014-03-18 14:01:45

标签: symfony doctrine-orm

如何使用DQL创建多个联接,如sql中所示:

SELECT t,c,u FROM `user` AS t
LEFT JOIN (`contract` AS c, `car` AS u) 
  ON (t.id = c.`user_id` AND u.id = c.`unit_id` AND u.name = 'audi')
WHERE t.email = 'test@example.com';

通过其他方式解决问题,创建子查询:

    $query = $this->createQueryBuilder('user')
        ->addSelect(
            array('contract', 'car')
        )
    ;
    $query->leftJoin(
        'user.contracts',
        'contract',
        Expr\Join::WITH,
        'contract.id IN (
               SELECT contract2.id
               FROM DataBundle:User user2
               INNER JOIN user2.contracts contract2
               INNER JOIN contract2.car car2
               WHERE user2.email = :email AND (
                    contract2.status = :status1 OR contract2.status = :status2
               ) AND car2.name = :name
        )'
    );
    $query->leftJoin(
        'contract.car',
        'car'
    );

    $query->where('user.email = :email');

也许对某人有用。

2 个答案:

答案 0 :(得分:1)

有关多个联接示例,请参阅article

DQL JOIN语法:

[[LEFT | INNER] JOIN <component_reference1>] [ON | WITH] <join_condition1> [INDEXBY] <map_condition1>,
[[LEFT | INNER] JOIN <component_reference2>] [ON | WITH] <join_condition2> [INDEXBY] <map_condition2>,
...
[[LEFT | INNER] JOIN <component_referenceN>] [ON | WITH] <join_conditionN> [INDEXBY] <map_conditionN>

答案 1 :(得分:0)

你最终会得到这样的东西:

SELECT user,contract,car 
FROM user AS user
LEFT JOIN user.contract AS contract
LEFT JOIN contract.car AS car
WHERE user.email = 'test@example.com' AND car.name = 'audi';

显然,您需要定义实体并正确设置关系。我建议按照文档中的示例进行操作,然后按照测试用例的方式进行操作。

请注意,对于别名使用缩写词(t,c,u)已被联合国宣布为战争罪,并将受到各种惩罚。