简体   繁体   中英

Equivalent mysql to eloquent query builder

I need to transform this query to the equivalent in Eloquent.

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

What I have so far.

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

I can't seem to group them country_id and add a count column that says how much there is of each.

For better readability, try combine with Carbon too, which is included with Laravel.

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

You can use the groupBy method, all of the methods are here: http://laravel.com/docs/queries (well, most of them).

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

If you wanted a count you can just do $seed->count() from here, and if you wanted a list of the country_id you could do $seed->lists('country_id') .

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM