为什么 laravel 在查询中覆盖两个不同的 veribales?

why laravel overwrite two different veribales in query?

我正在使用此查询在 $week_expence$month_expence

中获得 2 个不同的结果
 $week = \Carbon\Carbon::today()->subDays(7);
 $month = \Carbon\Carbon::today()->subDays(30);
 
 $expences =  SellerSell::where(['seller_id' => $id , 'order_confirmed_by' => $id ]);
 $week_expence = $expences->where('created_at','>=',$week)->sum('expenses');
 $month_expence = $expences->where('created_at','>=',$month)->sum('expenses');
 dd($week_expence , $month_expence);
    

考虑一下如果 $week_expence = 10 和 $month_expence = 20 那么我在周和月中得到的结果都是 10。为什么我在月中得到周费用?

您不能对两个不同的事物使用一个查询。

$week = \Carbon\Carbon::today()->subDays(7);
$month = \Carbon\Carbon::today()->subDays(30);
 
$week_expence =  SellerSell::where([
    'seller_id' => $id ,
    'order_confirmed_by' => $id
])
    ->where('created_at','>=',$week)
    ->sum('expenses');
$month_expence = SellerSell::where([
    'seller_id' => $id ,
    'order_confirmed_by' => $id
])
    ->where('created_at','>=',$month)
    ->sum('expenses');
dd($week_expence , $month_expence);

当然,您不需要重复代码,这就是 scopes 派上用场的地方:

class SellerSell extends Model
{
    public function scopeExpense($query, \Carbon\Carbon $date)
    {
        return $query->where([
            'seller_id' => $id,
            'order_confirmed_by' => $id
        ])
            ->where('created_at','>=',$date);
    }
}
$week = \Carbon\Carbon::today()->subDays(7);
$month = \Carbon\Carbon::today()->subDays(30);
 
$week_expence =  SellerSell::expense($week)->sum('expenses');
$month_expence = SellerSell::expense($month)->sum('expenses');
dd($week_expence , $month_expence);

Laravel 查询构建器是一个可变对象,这意味着每次添加 where 它都会更改查询构建器本身和 returns 对它的引用,因此当您调用 $expences->where('created_at','>=',$week) 它实际上修改了 $expences 实例。

以下是解决此问题并减少代码重复的方法:

 $week = \Carbon\Carbon::today()->subDays(7);
 $month = \Carbon\Carbon::today()->subDays(30);
 
 $expences =  SellerSell::where(['seller_id' => $id , 'order_confirmed_by' => $id ]);  
 $week_expence = (clone $expences)->where('created_at','>=',$week)->sum('expenses');

 $month_expence = (clone $expences)->where('created_at','>=',$month)->sum('expenses');
 dd($week_expence , $month_expence);

这将确保复制实例而不是原始实例发生变异。