问题描述
我想通过以下 SQL 使用 Eloquent ORM 获取价值.
I'd like to get value by the following SQL using Eloquent ORM.
- SQL
SELECT COUNT(*) FROM
(SELECT * FROM abc GROUP BY col1) AS a;
然后我考虑了以下内容.
Then I considered the following.
- 代码
$sql = Abc::from('abc AS a')->groupBy('col1')->toSql();
$num = Abc::from(DB::raw($sql))->count();
print $num;
我正在寻找更好的解决方案.
I'm looking for a better solution.
请告诉我最简单的解决方案.
Please tell me simplest solution.
推荐答案
除了@delmadord 的回答和您的评论:
In addition to @delmadord's answer and your comments:
目前没有在FROM
子句中创建子查询的方法,因此需要手动使用raw语句,然后,如果需要,您将合并所有绑定:
Currently there is no method to create subquery in FROM
clause, so you need to manually use raw statement, then, if necessary, you will merge all the bindings:
$sub = Abc::where(..)->groupBy(..); // Eloquent Builder instance
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
->count();
请注意,您需要以正确的顺序合并绑定.如果您有其他绑定子句,则必须将它们放在 mergeBindings
之后:
Mind that you need to merge bindings in correct order. If you have other bound clauses, you must put them after mergeBindings
:
$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
// ->where(..) wrong
->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
// ->where(..) correct
->count();
这篇关于如何使用 Laravel Query Builder 从子查询中进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!