How do I get a “select count(*) group by” using laravel eloquent

让人想犯罪 __ 提交于 2020-01-01 08:33:22

问题


I would like to execute the follow sentence using laravel eloquent

SELECT *, count(*) FROM reserves  group by day

The only solution occurs to me is to create a view in the DB, but I am pretty sure there is a way to do it in laravel way.


回答1:


You could use this:

$reserves = DB::table('reserves')->selectRaw('*, count(*)')->groupBy('day');



回答2:


As you wish to do it with Laravel Eloquent I assume you have a model name Reserve. In this case you can use this

$reserve = Reserve::all()->groupBy('day')->count();



回答3:


You could use:

#Laravel Raw Expressions

  $reserves = DB::table('reserves')
                       ->select(DB::raw('count(*) as reserves_count'))           
                       ->groupBy('day')
                       ->get();

OR

  $reserves = Reserve::select(['reserves.*'])
                       ->groupBy('day')
                       ->count();

Further read here



来源:https://stackoverflow.com/questions/34827917/how-do-i-get-a-select-count-group-by-using-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!