语义错误 - 学说 2.0



这些是我的表格:

    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('BBBGiftBundleEntityRegistry', '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 



我还想获得已购买礼物的总金额(如果有)
例如,总和(购买金额)作为总贡献

我试过:

    $qb = $this->createQueryBuilder('g')
    ->from('BBBGiftBundleEntityPurchase', 'p')
    ->from('BBBGiftBundleEntityRegistry', '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.

首先,你应该在连接后的 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 BBBGiftBundleEntityGift
    ->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 BBBGiftBundleEntityPurchase
    ->where('reg.couple = :coupleID')
    ->orderBy('reg.id','DESC')
    ->setParameter('coupleID', $coupleID);

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

还有一件事 - 如果您的存储库方法返回 X 实体的对象,您应该将此方法放入 XRepository。

相关内容

  • 没有找到相关文章

最新更新