我有两个表request
和request_reply
,这是LEFT 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'));
答案 0 :(得分: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');
让我们知道你是否正常工作。对关联映射有任何疑问,您可以找到here
<强> [编辑] 强>
尼克,请再试一次。第一个错误是因为我不知道您使用了别名回复。挑出来。第二个错误将在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');