语义错误 - Doctrine 2.0

时间:2012-10-14 02:25:11

标签: symfony doctrine-orm

这些是我的表格:

    Table Gift:
        -id 
        -price
        ... 


    Table Couple:
         -id
         -name 
        ... 


    table registry:  //provide a many-many relation between gifts and couples 
         -id 
         -coupleId 
         -giftId 


    table purchase:
         -amount
         -registryId 


我已经编写了一个sql查询来获取特定情侣的所有礼物信息

    $qb = $this->createQueryBuilder('g') //gift
    ->from('\BBB\GiftBundle\Entity\Registry', 'reg')
    ->select('g.id , g.price')
    ->where('reg.gift = g.id')
    ->andWhere('reg.couple = :coupleID')
    ->orderBy('reg.id','DESC')
    ->setParameter('coupleID', $coupleID);


或者是

     SELECT g.id , g.price,
    FROM gift g, registry reg       
    WHERE reg.gift_id = g.id AND reg.couple_id = 1 



我还想获得已购买礼品的总金额(如果有的话)
EX。 SUM(purchase.amount)为totalContribute

我试过了:

    $qb = $this->createQueryBuilder('g')
    ->from('\BBB\GiftBundle\Entity\Purchase', 'p')
    ->from('\BBB\GiftBundle\Entity\Registry', 'reg')
    ->select('g.id ,  g.price')
    ->addSelect('SUM(p.amount) as totalContribute')
    ->leftJoin('p','pp', 'ON','reg.id = pp.registry')
    ->where('reg.gift = g.id')
    ->andWhere('reg.couple = :coupleID')
    ->orderBy('reg.id','DESC')
    ->setParameter('coupleID', $coupleID);

但是它给了我以下错误:

    [Semantical Error] line 0, col 145 near 'pp ON reg.id': Error: Identification Variable p used in join path expression but was not defined before.

1 个答案:

答案 0 :(得分:2)

首先,您应该在连接之后在SQL语句中定义连接条件,而不是在WHERE子句中。原因是它真的没有效率。所以查询应该是这样的:

 SELECT g.id , g.price,
 FROM gift g JOIN registry reg ON reg.gift_id = g.id
 WHERE reg.couple_id = 1 

但是关于你的Doctrine查询,你得到错误,因为你以错误的方式定义连接。您的查询应该更像:

 $qb = $this->createQueryBuilder('g') // You don't have put "from" beacuse I assume you put this into GiftRepository and then Doctrine knows that should be \BBB\GiftBundle\Entity\Gift
    ->select('g.id ,  g.price')
    ->addSelect('SUM(p.amount) as totalContribute')
    ->join('g.purchase','p')          // pay attention for this line: you specify relation basing on entity property - I assume that is "$purchase" for this example        
    ->leftJoin('p.registry', 'reg')   // here you join with \BBB\GiftBundle\Entity\Purchase
    ->where('reg.couple = :coupleID')
    ->orderBy('reg.id','DESC')
    ->setParameter('coupleID', $coupleID);

请将此视为伪代码 - 我没有检查它是否有效,但它应该更像这样。

还有一件事 - 如果你的存储库方法返回X实体的对象,你应该把这个方法放到XRepository。