doctrine2(symfony2)多对多,带“WITH”和空值

时间:2014-03-18 07:57:21

标签: symfony doctrine-orm many-to-many left-join with-statement

我正在使用Symfony2 Framework并且在Doctrine数据库查询中遇到一些问题:

我已经定义了两个实体“客户”和“模块”,并在两者之间建立了多对多的关系。实际模块只有在为客户激活时才会存储到数据库中。

图像数据库如下所示:

Customer
|id|name|
100, foobar
200, foobar2
300, foobar3

Modul
|id|name|
1, modul1
2, modul2
3, modul3
4, modul4

(automatic generated m-to-n table)
Customer_Modul
|customer_id|modul_id|
100, 1
200, 2
200, 4
300, 4

现在我想查询特定客户及其模块。我需要一个左连接,因为只有在它们被激活时才存储模块。

我的查询代码如下所示:

$query = '
     SELECT m.id, m.name, CASE WHEN c.id IS NULL THEN FALSE ELSE TRUE END as active
            FROM MyNamespace:Modul m
            LEFT JOIN m.customers c WITH c.id = :id
   ';

   $queryObj = $this->doctrine->getManager()->createQuery($query);
   $queryObj->setParameter('id', $id);
   $modules = $queryObj->getResult();

我的问题现在如下:内部这个本机查询由doctrine:

组成
SELECT 
  m0_.id AS id0, 
  m0_.name AS name1, 
  CASE WHEN c1_.id IS NULL THEN 0 ELSE 1 END AS sclr2 
FROM 
  modul m0_ 
  LEFT JOIN customer_modul c2_ ON m0_.id = c2_.modul_id 
  LEFT JOIN customer c1_ ON c1_.id = c2_.customer_id 
  AND (c1_.id = ?) 

但我真正需要的本机查询就是这个:

SELECT 
  m0_.id AS id0, 
  m0_.name AS name1, 
  CASE WHEN c1_.id IS NULL THEN 0 ELSE 1 END AS sclr2 
FROM 
  modul m0_ 
  LEFT JOIN customer_modul c2_ ON m0_.id = c2_.modul_id 
  AND (c2_.customer_id = ?)
  LEFT JOIN customer c1_ ON c1_.id = c2_.customer_id 

有没有人知道如何使用原生教条查询除外?

非常感谢你的帮助,

1 个答案:

答案 0 :(得分:0)

您可能想尝试

SELECT m.id, m.name, 
    (SELECT c.id FROM YourNamespace:Customers c JOIN c.modules m2 
     WHERE m2.id = m.id and c.id = :customerId) AS checked
FROM YourNamespace:Modul m