Laravel 根據 relation sum 結果排序的小技巧

Hanson發表於2020-03-25

最近專案遇到的小問題,找了一下發現了新姿勢

原文:https://www.itsolutionstuff.com/post/larav...

  • 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);
本作品採用《CC 協議》,轉載必須註明作者和本文連結

提供優質的軟體服務

相關文章