等效的mysql到eloquent查询构建器

时间:2014-06-18 13:56:05

标签: php mysql laravel eloquent

我需要将此查询转换为Eloquent中的等效项。

SELECT country_id, count(*) as count
FROM seeds
WHERE seeds.created_at > date_sub(NOW(), interval 24 hour)
GROUP BY country_id

到目前为止我所拥有的。

$seed = Seed::select('*')->where("created_at", ">", DB::raw('(NOW() - INTERVAL 24 HOUR)'))
        ->get();

我似乎无法将它们分组为country_id,并添加一个计数列,其中显示每个列的数量。

2 个答案:

答案 0 :(得分:1)

为了更好的可读性,请尝试与碳一起使用,这也包含在Laravel中。

Seed::select(array(
    'country_id',
    DB::raw('COUNT(*) as count'))
->where('created_at', '>', Carbon::now()->subHours(24))
->groupBy('country_id')
->get();

答案 1 :(得分:0)

您可以使用groupBy方法,所有方法都在这里:http://laravel.com/docs/queries(嗯,大多数方法)。

$seed = Seed::whereCreatedAt('>', DB::raw('(NOW() - INTERVAL 24 HOUR)'))->groupBy('country_id')->get();

如果您想要统计,可以从这里开始$seed->count(),如果您想要country_id的列表,可以$seed->lists('country_id')

希望有所帮助。