You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DB原生查询代码转换为Laravel Eloquent模型方法

转换原生查询为Laravel Eloquent模型方法

嘿,我来帮你把这段原生查询转换成更优雅、更符合Laravel Eloquent风格的写法,还能封装成模型方法方便复用!

单个查询的优化写法

原来的查询用了DB::raw和array_column,我们可以用Eloquent提供的selectRaw、groupByRaw和pluck方法来简化:

统计每年的numberofview总和

$match = DiraChatLog::selectRaw('SUM(numberofview) as count')
    ->orderBy('created_at')
    ->groupByRaw('YEAR(created_at)')
    ->pluck('count')
    ->toArray();

统计每年的numberofclick总和(补全你未写完的部分)

$missing = DiraChatLog::selectRaw('SUM(numberofclick) as count')
    ->orderBy('created_at')
    ->groupByRaw('YEAR(created_at)')
    ->pluck('count')
    ->toArray();

封装成模型方法(推荐)

为了让代码更复用、更符合Laravel的MVC设计,我们可以把这些查询逻辑封装到DiraChatLog模型里:

打开你的app/Models/DiraChatLog.php,添加两个静态方法:

/**
 * 获取每年的浏览量统计数组
 */
public static function getYearlyViewCounts()
{
    return self::selectRaw('SUM(numberofview) as count')
        ->orderBy('created_at')
        ->groupByRaw('YEAR(created_at)')
        ->pluck('count')
        ->toArray();
}

/**
 * 获取每年的点击量统计数组
 */
public static function getYearlyClickCounts()
{
    return self::selectRaw('SUM(numberofclick) as count')
        ->orderBy('created_at')
        ->groupByRaw('YEAR(created_at)')
        ->pluck('count')
        ->toArray();
}

之后在控制器或者其他地方调用就非常简洁了:

$match = DiraChatLog::getYearlyViewCounts();
$missing = DiraChatLog::getYearlyClickCounts();

为什么这么写?

  • selectRaw和groupByRaw比嵌套DB::raw更直观,符合Eloquent的链式调用风格
  • pluck('count')直接提取统计结果的count字段,省去了get()->toArray()再用array_column转换的步骤
  • 封装成模型方法后,查询逻辑集中在模型里,后续修改统计规则只需要改模型,不用到处找代码

内容的提问来源于stack exchange,提问作者Rajveer Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:11:05