首页 > 上网技巧 > 电脑小技巧 > Laravel 根据 relation sum 结果排序的小技巧

Laravel 根据 relation sum 结果排序的小技巧

时间:2020-08-05 11:43 作者:QQ地带 我要评论

laravel 6
$customers = Customer::addSelect(['balance' => CustomerBalance::selectRaw('sum(amount) as total')
         ->whereColumn('customer_id', 'customers.id')
         ->groupBy('customer_id')
     ])
     ->orderBy('balance', 'DESC')
     ->get()
     ->toArray();
 
dd($customers);
laravel 5
$customers = User::select("*", \DB::raw('(SELECT SUM(amount) FROM customer_balances WHERE customer_balances.customer_id = customers.id) as balance'))
    ->orderBy('balance', 'DESC')
    ->get()
    ->toArray();
 
dd($customers);
 
 

标签: laravel
顶一下
(0)
0%
踩一下
(0)
0%

Google提供的广告