在Eloquent

时间:2017-01-03 16:56:28

标签: mysql laravel eloquent

我正在尝试加速我的应用程序,并对单个Eloquent查询执行操作有疑问。

我需要绘制一个包含不同总数的表格。

        $records = $this->finance
                        ->where('company_id','=',$this->company_id)
                        ->where(DB::raw('MONTH(date)'), '=', $month['month'])
                        ->where(DB::raw('YEAR(date)'), '=', $year)
                        ->where('financeaccounts_id', '=', $account);

        $income = $records->where('type','=','Income')->sum('amount');
        $expense = $records->where('type','=','Expense')->sum('amount');
        $correction = $records->where('type','=','Correction')->sum('amount');  

'收入'正确计算,但随后的'总和' AREN'吨。我猜测每个作业都在修改查询。我很感激你的帮助。 感谢

3 个答案:

答案 0 :(得分:0)

是的,你修改了查询是对的。要解决此问题,您可以将查询克隆为:

$income_records = clone $records;
$expense_records = clone $records;
$correction_records = clone $records;

$income = $income_records->where('type','=','Income')->sum('amount');
$expense = $expense_records->where('type','=','Expense')->sum('amount');
$correction = $correction_records->where('type','=','Correction')->sum('amount');

答案 1 :(得分:0)

我认为更好的方法是只运行一个查询而不是3个,然后使用集合:

$records = $this->finance
    ->where('company_id','=',$this->company_id)
    ->where(DB::raw('MONTH(date)'), '=', $month['month'])
    ->where(DB::raw('YEAR(date)'), '=', $year)
    ->where('financeaccounts_id', '=', $account)
    ->get();

    $income = $records->where('type', 'Income')->sum('amount');
    $expense = $records->where('type', 'Expense')->sum('amount');
    $correction = $records->where('type', 'Correction')->sum('amount');

在此代码中,您使用sum()收集方法而不是查询构建器的sum()方法。这种方法不会创建三个查询,只会创建一个。

答案 2 :(得分:0)

您还可以使用子查询在一个查询中完成所有操作:

$records = $this->finance
                    ->select('finances.*')
                    ->selectSub(function($query) {
                        return $query->selectRaw('SUM(amount)')
                            ->where('type', '=', 'Income');
                    }, 'income_sum')
                    ->selectSub(function($query) {
                        return $query->selectRaw('SUM(amount)')
                            ->where('type', '=', 'Expense');
                    }, 'expense_sum')
                    ->selectSub(function($query) {
                        return $query->selectRaw('SUM(amount)')
                            ->where('type', '=', 'Correction');
                    }, 'correction_sum')
                    ->where('company_id','=',$this->company_id)
                    ->whereMonth('date' $month['month'])
                    ->whereYear('date' $year)
                    ->where('financeaccounts_id', '=', $account)
                    ->get();                  

$income = $records->income_sum;
$expense = $records->expense_sum;
$correction = $records->correction_sum;