I have two simple entities:
My\Entity\Coupon:
type: entity
table: coupon
id:
id:
type: integer
generator:
strategy: AUTO
fields:
name:
type: string
length: 255
nullable: false
value:
type: integer
default: 0
My\Entity\CouponUsers:
type: entity
table: coupon_users
id:
id:
type: integer
length: 11
nullable: false
generator:
strategy: AUTO
fields:
coupon_id:
type: integer
length: 11
nullable: false
user_id:
type: integer
Now, I want to display simple stats for used coupons.
Running this SQL in phpMyAdmin:
SELECT c.name, count( * ) AS mycount
FROM coupon c
LEFT JOIN coupon_users u ON c.id = u.coupon_id
GROUP BY c.id
ORDER BY mycount DESC
Works fine as expected, returns:
name1 54
name2 120
Then, I try to do the same from Doctrine 2:
$queryBuilder = $this->_em->createQueryBuilder()
->select('c.name, COUNT(*) as co')
->from('My\Entity\Coupon', 'c')
->leftJoin('My\Entity\CouponUsers', 'u',
\Doctrine\ORM\Query\Expr\Join::ON, 'c.id = u.coupon_id')
->where('u.coupon_id = c.id')
->groupBy('c.id');
$dql = $queryBuilder->getDQL();
var_dump($dql);
SELECT c.name,
COUNT(*) as co
FROM My\Entity\Coupon c
LEFT JOIN My\Entity\CouponUsers u
ON c.id = u.coupon_id
WHERE u.coupon_id = c.id
GROUP BY c.id
So far, so good. But when I do:
$queryBuilder->getQuery()->getResult();
I get error:
[Syntax Error] line 0, col 88: Error: Expected Doctrine\ORM\Query\Lexer::T_DOT, got 'u'
What’s wrong? How can I fix this?
Here is how the Doctrine manual would suggest coding your query:
To perform this join in QueryBuilder, you’ll need a bidirectional association configured between the two entities, which you don’t seem to have set up yet.
I use annotations for my entities, but I think the YAML will look something like this:
If users can have many coupons, then the relationship would be bidirectional ManyToMany instead of manytoOne/oneToMany. The details on how to configure this can be found here.