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

2019-04-06 10:17发布

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.

3条回答
可以哭但决不认输i
2楼-- · 2019-04-06 10:46

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-06 10:58

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();
查看更多
倾城 Initia
4楼-- · 2019-04-06 11:01

You could use this:

$reserves = DB::table('reserves')->selectRaw('*, count(*)')->groupBy('day');
查看更多
登录 后发表回答