2011-11-16 49 views
3

我有两个简单的实体:leftJoin教义2

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 

现在,我想显示二手券简单的统计。
运行该SQL在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 

如预期工作正常,返回:

name1 54 
name2 120 

然后,我尝试从学说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' 

有什么不对?我怎样才能解决这个问题?

回答

6

这里是教义手册将如何建议编码查询:

$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 

如果用户可以有很多优惠券,那么关系是双向多对多的而不是多对一/一对多。有关如何配置的详细信息,请参见here

+0

谢谢。我怎样才能通过'co'添加订单?在'co DESC'附近添加' - > orderBy('co','DESC')'返回'[语义错误]行0,列91':错误:'counter'未定义。 ' - > orderBy('COUNT(c.id)')' – Sfisioza

+0

你输入的内容 - > orderBy('co','DESC')是正确的,应该可以工作。检查明显的第一个:orderBy()需要在groupBy()之后出现,并且您在select()中使用的别名需要与orderBy()中使用的别名相匹配。从错误消息中,您可能已经使用了别名。如果它还没有合作,我很高兴看看你的代码。 – cantera

+0

谢谢。这确实是我的代码的问题。 – Sfisioza