如果组计数大于某个数字,如何对LLAVEL中的项目进行分组并回显该值

2022-03-27 00:00:00 sql php laravel laravel-8
$sql = "SELECT COUNT(date) AS numberofreservations, date FROM reservations GROUP BY date HAVING numberofreservations >= $max";//#per day

我刚刚切换到laravel,我正在尝试基于此SQL获取一个变量,$max应该在控制器中,来自我已经获得的另一个数据库,但是DOI如何将它们像这样分组呢?


解决方案

口才:

$max = 1; // example
$sql = Reservation::selectRaw('count(date) as numberofreservations, date')
    ->groupBy('date')
    ->havingRaw('numberofreservations >= ' . $max)
    ->get();

或查询生成器:

$max = 1; // example
$sql = DB::table('reservations')
    ->selectRaw('count(date) as numberofreservations, date')
    ->groupBy('date')
    ->havingRaw('numberofreservations >= ' . $max)
    ->get();

调试:

$sql = DB::table('reservations')
    ->selectRaw('count(date) as numberofreservations, date')
    ->groupBy('date')
    ->havingRaw('numberofreservations >= ' . $max)
    ->dd();
"select count(date) as numberofreservations, date from `reservations` group by `date` having numberofreservations >= 1"
[]

相关文章