0

我有两个表,request这里request_replyLEFT JOIN选择请求以及回复数量的查询:

SELECT request.id, COUNT(request_reply.id) as replies
FROM request LEFT JOIN request_reply ON request.id = request_reply.request_id
GROUP BY `request`.`id`
ORDER BY replies ASC

但是当我尝试将其编写为 Doctrine 查询时:

$query = Doctrine_Query::create()
         ->select('Request.id, COUNT(RequestReply.id) as reply_count')
         ->from('Request')
         ->leftJoin('RequestReply ON Request.id = RequestReply.request_id')
         ->groupBy('Request.id')
         ->orderBy('reply_count ASC, Request.id DESC');

结果没有LEFT JOIN

SELECT `r`.`id` AS `r__id`, COUNT(`r2`.`id`) AS `r2__0` 
FROM `request` `r`, `request_reply` `r2`
GROUP BY `r`.`id`
ORDER BY `r2__0` ASC, `r`.`id` DESC

我不明白出了什么问题,我已经尝试了所有方法,但是JOIN无论我做什么,结果查询中都没有。这是一个带有 Doctrine 1 的遗留项目,所以我无法更新到 Doctrine 2。

更新

映射。

Request.php

$this->hasMany('RequestReply as Replies', array('local' => 'id', 'foreign' => 'request_id'));

RequestReply.php

$this->hasOne('Request', array('local' => 'request_id', 'foreign' => 'id'));
4

1 回答 1

0

您是否正确映射了您的实体?我想在您的实体请求中,您有一个 OneToMany 注释或指向实体 RequestReply 的任何其他 (YAML..)。如果是这样,你应该能够实现你正在寻找的只是这样做:

$query = Doctrine_Query::create()
         ->select('Request.id, COUNT(rp.id) as reply_count')
         ->from('Request r')
         ->leftJoin('r.RequestReply rp')
         ->groupBy('r.id')
         ->orderBy('reply_count ASC, r.id DESC');

让我知道你是否成功了。您可以在此处找到对关联映射的任何疑问

[编辑]

尼克,请再试一次。第一个错误是因为我不知道您使用了别名回复。挑出来。第二个错误将随着 SELECT 中的字段 r.id 消失。;-)

$query = Doctrine_Query::create()
         ->select('r.id, COUNT(rp.id) as reply_count')
         ->from('Request r')
         ->leftJoin('r.Replies rp')
         ->groupBy('r.id')
         ->orderBy('reply_count ASC, r.id DESC');
于 2013-04-21T04:51:13.613 回答