You might want to try
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
题
I'm using Symfony2 Framework and having some trouble with a Doctrine database query:
I have defined two Entitys "customer" and "modules" and setup a many-to-may relationship between both. actualy modules are only stored to database if they are activated for the customer.
Image data base looks like this:
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
Now I want to query a specific customer and its modules. I need a left join, because modules are only stored if they are actived.
My query code looks like this:
$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();
My Problem now is the following: Internally this native Query is made by 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 = ?)
But the native query i actually need is this one:
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
Has anybody an idea how to do this except using a native doctrine query?
Thanks you already for your help,
Susa
解决方案
You might want to try
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