Mysql 左联主义2

Mysql 左联主义2,mysql,sql,doctrine-orm,Mysql,Sql,Doctrine Orm,我有两个简单的实体: My\Entity\Coupon: type: entity table: coupon id: id: type: integer generator: strategy: AUTO fields: name: type: string length: 255 nullable: false v

我有两个简单的实体:

  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
然后,我试着从教义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'

怎么了?如何解决此问题?

以下是条令手册建议如何对查询进行编码:

$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。可以找到有关如何配置此功能的详细信息。

谢谢。如何通过
co
添加订单?添加
->orderBy('co','DESC')
返回
[语义错误]第0行,第91列“co DESC”附近:错误:“计数器”未定义。
。同样的,您键入的->orderBy('COUNT(c.id)'是正确的,应该可以工作。首先检查明显的:orderBy()需要位于groupBy()之后,并且在select()中使用的别名需要与orderBy()中使用的别名匹配。从错误消息中,您可能使用了不同的别名。如果它仍然不合作,我很乐意看看你的代码。