Reputation: 366
orders
id - integer
client_id - integer
clients
id - integer
name - string
accounts
id - integer
client_id - integer
amount - integer
$orders = Order::with(['transaction', 'client', 'delivery', 'address'])
->latest()->paginate(50);
return view('admin.order.index', compact('orders'));
<td class="text-center">
<strong>{{$item->client->invoice}}</strong>
</td>
public function getInvoiceAttribute()
{
return $this->account()->sum('amount');
}
I don't know how to use Has Many Through. Or how to solve this situation I don't need an account at the front but I need sum of amounts
Upvotes: 0
Views: 108
Reputation: 366
Schema::table('clients', function (Blueprint $table) {
$table->integer('invoice')->default(0);
});
class AccountObserver
{
public function creating(Account $account)
{
$account->client()->increment('invoice',$account->amount);
}
public function updating(Account $account)
{
$account->client()->increment('invoice',$account->amount);
}
}
$orders = Order::with(['transaction', 'client', 'delivery', 'address'])
->latest()->paginate(50);
return view('admin.order.index', compact('orders'));
<td class="text-center">
<strong >{{$item->client->invoice}}</strong>
</td>
Upvotes: 1
Reputation: 15786
$this->account()->sum('amount');
This creates a SQL query. If you call it in a foreach loop, it will do N Queries.
You could eager load the sum.
$orders = Order::query()
->with([
'transaction',
'client' => fn ($client) => $client->withSum('accounts as invoice', 'amount'), // or function ($client) { $client->withSum('accounts as invoice', 'amount'); },
'delivery',
'address'
])
->latest()
->paginate(50);
return view('admin.order.index', compact('orders'));
@foreach ($orders as $item)
...
<td class="text-center">
<strong>{{ $item->client->invoice }}</strong>
</td>
...
@endforeach
Remove the getInvoiceAttribute
method from the Client
Model
Upvotes: 0