在laravel中编写一个查询join sum groupby

Але*_*зов 4 join sum laravel


请帮我写查询。
我有 2 个表:“项目”和“债务”
“债务”表有

id | project_id | currency_list | total
1  | 1          | 1             | 1000
2  | 1          | 2             | 500
3  | 2          | 1             | 1000
4  | 2          | 2             | 500
...
Run Code Online (Sandbox Code Playgroud)

我需要编写查询以从项目中获取 1000 行,并将所有“总计”与“currency_list”组相加

非常感谢 :)

Ham*_*raj 7

嘿,我为你试过它希望工作:) 首先你应该有两个表格模型在你的项目模型调用中

    public function debts(){
      return $this->hasMany('App\Debt','project_id')->selectRaw('debts.*,sum(total) as sum')->groupBy('currency_list');
   }
Run Code Online (Sandbox Code Playgroud)

并在您的控制器中调用它

$projects = Project::with('debts')->get()->toArray();
Run Code Online (Sandbox Code Playgroud)

检查你的dd($projects)作为数组

编辑:在您的控制器功能中使用它

$projects = DB::table('projects')
            ->join('debts', 'projects.id', '=', 'debts.projects_id')
            ->select('projects.*','debts.*', DB::raw('sum(total) as sum'))
            ->groupBy('currency_list')
            ->get();
Run Code Online (Sandbox Code Playgroud)

然后在您看来使用

@foreach($projects as $project)
{
{{$project->sum}}
}
Run Code Online (Sandbox Code Playgroud)