【问题标题】:Equivalent mysql to eloquent query builder等效于 mysql 到 eloquent 查询生成器
【发布时间】:2014-06-18 13:56:05
【问题描述】:

我需要将此查询转换为 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 并添加一个计数列来说明每个的数量。

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    为了更好的可读性,也可以尝试与 Laravel 中包含的 Carbon 结合使用。

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

    【讨论】:

      【解决方案2】:

      您可以使用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')

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-18
        • 2017-08-31
        • 1970-01-01
        • 2014-05-13
        • 2015-02-02
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多