我试图在行结果内执行avg和计数查询,类似于:
SELECT r.id, avg( p.puntuacio ), count(p.puntuacio)
FROM receptes AS r, puntuacio_receptes_usuaris AS p
WHERE r.id = p.recepta_id
GROUP BY r.id
但我不知道我可以在Laravel上做,因为在Eloquent中不能在结果行中写avg或count。
Thanks to lot
查询生成器(Fluent)方法:
DB::table(DB::raw('receptes as r, puntuacio_receptes_usuaris as p'))
->select(array('r.id', DB::raw('avg( p.puntuacio ) as avg_p'), DB::raw('count(p.puntuacio) as count_p')))
->where('r.id', DB::raw('p.recepta_id'))
->groupBy('r.id')
->get();
这应该没有任何问题,但如果你想在你的Eloquent模型中这样做,我建议使用JOIN
而不是在FROM
中使用两个表。
可以通过访问avg_p
和count_p
来访问avg和计数结果。
注意:
-
DB::raw()
指示Laravel不要逃离里面的内容,参见文档。
如果需要使用Eloquent会转义的东西,可以使用DB::raw()
来创建原始表达式。
关于一些例子,请参考原始表达式的文档