首页 文章

将我的DB raw转换为Laravel Eloquent模型

提问于
浏览
1

我有一个教程的代码,我想知道如何将它转换为laravel eloquent方法,因为目前它是在DB原始方法 .

// $match = DiraChatLog::select(DB::raw("SUM(numberofview) as count"))
//     ->orderBy("created_at")
//     ->groupBy(DB::raw("year(created_at)"))
//     ->get()->toArray();
// $match = array_column($match, 'count');

// $missing = DiraChatLog::select(DB::raw("SUM(numberofclick) as count"))
//     ->orderBy("created_at")
//     ->groupBy(DB::raw("year(created_at)"))
//     ->get()->toArray();
// $missing = array_column($missing, 'count');

// $noAnswer = DiraChatLog::select(DB::raw("SUM(numberofclick) as count"))
//     ->orderBy("created_at")
//     ->groupBy(DB::raw("year(created_at)"))
//     ->get()->toArray();
// $noAnswer = array_column($noAnswer, 'count');

2 回答

  • 0

    如果你只想得到你的列的总和,你可以调用 sum 方法而不是 get 这样

    DiraChatLog::sum('yourColumn'); // will return the only sum
    

    检查enter link description here中的聚合方法

  • 0

    此示例取自可在此处找到的laravel文档:https://laravel.com/docs/5.6/eloquent

    $count = App\Flight::where('active', 1)->count();
    

    在此示例中,App \ Flight是已连接到表的模型 .

    where方法非常明显,我们希望得到列活动为1的数据 .

    count方法也很明显,它允许我们计算所有数据并返回行数 .

相关问题