我有两个简单的实体:
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
现在,我想显示使用过的优惠券的简单统计数据 在phpMyAdmin中运行此SQL:
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
按预期正常工作,返回:
name1 54
name2 120
然后,我尝试从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
到目前为止,这么好。但是当我这样做时:
$queryBuilder->getQuery()->getResult();
我收到错误:
[Syntax Error] line 0, col 88: Error: Expected Doctrine\ORM\Query\Lexer::T_DOT, got 'u'
怎么了?我该如何解决这个问题?
答案 0 :(得分:6)
以下是Doctrine手册建议对您的查询进行编码的方式:
$querybuilder = $this->_em->createQueryBuilder()
->select(array('c.name', 'COUNT(c.id) as co')
->from('My\Entity\Coupon', 'c')
->leftJoin('c.users', 'u')
->groupBy('c.id');
要在QueryBuilder中执行此连接,您需要在两个实体之间配置双向关联,您似乎尚未设置它们。
我为我的实体使用注释,但我认为YAML看起来像这样:
My\Entity\Coupon:
manyToOne:
users:
targetentity: CouponUsers
inversed-by: coupon
My\Entity\CouponUsers:
onetoMany:
coupon:
targetEntity: Coupon
mapped-by: users
如果用户可以拥有许多优惠券,那么这种关系将是双向的ManyToMany而不是manytoOne / oneToMany。有关如何配置此内容的详细信息,请参见here。