我有实体
Template {
/**
* @ORM\OneToMany(targetEntity="TemplateSnapshot", mappedBy="template", cascade={"all"})
*/
protected $snapshots;
}
/**
* @ORM\Entity
*/
class TemplateSnapshot {
/**
* @ORM\Column(type="datetime")
* @var \DateTime
*/
protected $modTime;
}
并尝试获取由modTime在TemplateSnapshot中排序的模板
QueryBuilder $query
->leftJoin('EditorBundle:TemplateSnapshot','s','WITH', $tableAlias.'.id = s.template_id')
->groupBy($tableAlias.'.id')
->orderBy('s.modTime','desc')
;
我得到了
选择t0_.id作为id0,t0_.location作为location1,t0_.name作为name2,t1_.modTime作为modTime3从模板t0_左加入TemplateSnapshot t1_ ON t0_.id = t1_.template_id左加入TemplateSnapshot t2_ ON (t0_.id = t2_.template_id),t2_喜欢哪种?按t0_.id顺序分组由t2_.modTime DESC限制20
此返回第一个联接行。(第一组,然后排序)。我想加入最新的TemplateSnapshot
其他尝试
$query
->leftJoin('TemplateEditorBundle:TemplateSnapshot',
's',
'WITH',
$tableAlias.'.id = s.template_id and s.modTime = MAX(s.modTime)'
)
->groupBy($tableAlias.'.id')
->orderBy('s.modTime','desc')
;
我得到了这个:
选择t0_.id作为id0,t0_.location作为location1,t0_.name作为name2,t1_.modTime作为modTime3,MAX( t2_.modTime )作为sclr4从模板t0_左加入TemplateSnapshot t1_ ON t0_.id = t1_.template_id左连接TemplateSnapshot t2_ ON (t1_.template_id=t2_和=MAX()),其中喜欢?由t2_.modTime DESC限价20订购
和错误
组函数的enter code here
无效使用
其他想法
我尝试直接查询TemplateSnapshot
$source = new Entity('TemplateEditorBundle:TemplateSnapshot');
$query
->orderBy($tableAlias.'.modTime','desc') ->groupBy($tableAlias.'.template_id')
;
但是,它首先抢购,然后订购,所以不要得到最新的。
发布于 2014-10-17 01:40:33
为此,您需要实现本机查询。查询应该如下所示:
SELECT * FROM TemplateSnapshot ts
INNER JOIN
(SELECT MAX(mod_time) AS mod_time, template_id FROM TemplateSnapshot GROUP BY template_id) AS ts_max
ON ts.template_id = ts_max.template_id AND ts.mod_time = ts_max.mod_time
此查询将仅为每个mod_time
从TemplateSnapshot
返回最大值为Template
的行。
https://stackoverflow.com/questions/26420170
复制相似问题