使用 Laravel 获取总记录数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22748084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get total number of records with Laravel?
提问by mpen
MySQL has a feature for getting the total number of records a query would return without a limit, SQL_CALC_FOUND_ROWS
. Does Laravel support this?
MySQL 具有获取查询将无限制返回的记录总数的功能,SQL_CALC_FOUND_ROWS
. Laravel 支持吗?
Currently I have to do it in two queries:
目前我必须在两个查询中做到这一点:
public function dataTable() {
$bookings = DB::table('bookings')
->limit(Input::query('iDisplayLength'))
->offset(Input::query('iDisplayStart'))
->get();
$count = $bookings = DB::table('bookings')
->count();
return Response::json([
'iTotalRecords' => $count,
]);
}
Not only will this be less efficient, but there's going to be a lot of redundant code once I add in all the ->where()
criteria.
这不仅会降低效率,而且一旦我添加了所有->where()
标准,就会有很多冗余代码。
回答by giaour
For any complicated or vendor-specific queries, you generally have to pass the query directly with DB::raw()
, e.g.:
对于任何复杂的或特定于供应商的查询,您通常必须直接使用 传递查询DB::raw()
,例如:
$bookings = DB::table('bookings')
->select(DB::raw('SQL_CALC_ROWS_FOUND ...
回答by kamlesh.bar
Refined what @giaour said.
完善@giaour 所说的内容。
$bookings = DB::table('bookings')
->select(array(DB::raw('SQL_CALC_FOUND_ROWS booking_id,name')))
->where('...')
->orWhere('...')
->take(10)
->skip(50)
->get();
$bookingsCount = DB::select( DB::raw("SELECT FOUND_ROWS() AS Totalcount;") );
After SQL_CALC_FOUND_ROWS you can fetch count by SQL_CALC_FOUND_ROWS();
在 SQL_CALC_FOUND_ROWS 之后,您可以通过 SQL_CALC_FOUND_ROWS(); 获取计数;
回答by Paul
I came across this issue because I wanted to paginate a set of results which already included a GROUP BY and Laravel's built-in paginate() method uses COUNT(*) and doesn't work with GROUP BY.
我遇到了这个问题,因为我想对已经包含 GROUP BY 的一组结果进行分页,而 Laravel 的内置 paginate() 方法使用 COUNT(*) 并且不适用于 GROUP BY。
So I ended up extending the Builder class to inject the SQL_CALC_FOUND_ROWS right before a query is run, and run FOUND_ROWS right after. I did this by overriding the Laravel getModels() method.
所以我最终扩展了 Builder 类,在查询运行之前注入 SQL_CALC_FOUND_ROWS,然后立即运行 FOUND_ROWS。我通过覆盖 Laravel getModels() 方法来做到这一点。
I've uploaded the code here.
我已经在这里上传了代码。