Laravel Order By Relationship Sum Column Example
https://www.itsolutionstuff.com/post/laravel-order-by-relationship-sum-column-exampleexample.html
Laravel Order By Relationship Sum Column Example
$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);$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);array:2 [▼ 0 => array:7 [▼ "id" => 2 "name" => "Paresh" "email" => "test@gmail.com" "email_verified_at" => null "created_at" => "2019-09-14 03:10:38" "updated_at" => "2019-09-14 03:10:38" "balance" => "50" ] 1 => array:7 [▼ "id" => 1 "name" => "Hardik" "email" => "savanihd@gmail.com" "email_verified_at" => null "created_at" => "2019-09-14 03:10:38" "updated_at" => "2019-09-14 03:10:38" "balance" => "30" ]]Previous[WITH] Laravel Order By Relation Column ExampleNextLaravel Copy Record using Eloquent Replicate Example
Last updated