如何使用 Laravel eloquent 获得“选择计数(*)组”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34827917/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:14:00  来源:igfitidea点击:

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

laravellaravel-5eloquentquery-builder

提问by Ugo Guazelli

I would like to execute the follow sentence using laravel eloquent

我想使用 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.

我想到的唯一解决方案是在数据库中创建一个视图,但我很确定有一种方法可以用 laravel 的方式来做到这一点。

回答by Marcin Nabia?ek

You could use this:

你可以用这个:

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

回答by smartrahat

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

当您希望使用 Laravel Eloquent 时,我假设您有一个模型名称Reserve。在这种情况下,您可以使用此

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

回答by Khine Thu

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

进一步阅读这里