I have a table for my categories, each category have and id, name and parent_id.
Select IF(a.parent_id IS NULL, a.name, CONCAT((SELECT b.name FROM category b WHERE b.id = a.parent_id), " / ", a.name) ) as n, a.id, a.parent_id
FROM category a
ORDER BY n
I want to convert it to my Doctrine2 Query Builder
$em = $this->getDoctrine()->getEntityManager();
$qb = $em->createQueryBuilder();
$q = $qb
->select("c.id")
->addSelect(
"IF(c.parent_id IS NULL, c.name, CONCAT((" .
$em->createQueryBuilder()
->select("t.name")
->from("MyBundle:Category", "t")
->getQuery()->getDQL() .
"), \" / \", c.name) )"
)
->from("MyBundle:Category", "c");
echo $q->getQuery()->getSQL();
exit;
Something like that, but I cant use the IF
, and CONCAT
.
Assuming you have a relation named "parent" in Category, does this work better? :
Ok I found the solution.
You can use
CASE
instead ofIF
. Check this out, but when I am usingCASE
I can'tCONCAT
my fields:Another Solution is create your own DQL function, like
IF
and use it like this:For create this IF you can go to this link and learn: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#adding-your-own-functions-to-the-dql-language
I will post here my class for this IF and the config.yml to help other people. Here is the IfFunction class (I got that from https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Mysql/IfElse.php):
After that you need to update your config.yml like this (just added the last 3 lines):
Thanks
You can also combine
CASE
andCONCAT
: