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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39369044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:25:59  来源:igfitidea点击:

Write a query join sum groupby in laravel

laraveljoinsum

提问by Алексей Морозов


Please help me write query.
I have 2 table: "projects" and "debts"
"debts" table have


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

id | project_id | currency_list | total
1  | 1          | 1             | 1000
2  | 1          | 2             | 500
3  | 2          | 1             | 1000
4  | 2          | 2             | 500
...

I need write query to take 1000 rows from projects and SUM all "total" with group by "currency_list"

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

Thanks a lot :)

非常感谢 :)

回答by Hamelraj

Hey i tried for you its hope working :) First you should have tow models for tables In your Project model call like this

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

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

and call this in your controller

并在您的控制器中调用它

$projects = Project::with('debts')->get()->toArray();

check your dd($projects)as array

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

EDIT : Use this in your controller function

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

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

then in your view use

然后在您看来使用

@foreach($projects as $project)
{
{{$project->sum}}
}

回答by Parithiban

You can try this

你可以试试这个

App/Project

应用程序/项目

public function getDebts()
{
    return $this->hasMany('App\Debt');
}

Controller

控制器

use App\Project;

public function getProjects(Project $project ) 
{        
    $all =  $project->with(['getDebts'=>function($query){
                $query->selectRaw('*,sum(total) as sum')
                      ->groupBy('currency_list');
            }])->take(1000);
}