Home > Software engineering >  reducing the number of sql queries from the front
reducing the number of sql queries from the front

Time:03-01

    orders
        id - integer
        client_id - integer
     
    clients
        id - integer
        name - string
     
    accounts
        id - integer
        client_id - integer
        amount - integer

Controller

$orders = Order::with(['transaction', 'client', 'delivery', 'address'])
  ->latest()->paginate(50);
return view('admin.order.index', compact('orders'));

FrontEnd

      <td >
        <strong>{{$item->client->invoice}}</strong>
      </td>

Client Model

  public function getInvoiceAttribute()
  {
    return $this->account()->sum('amount');
  }

enter image description here

I don't know how to use enter image description here

CodePudding user response:

$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 >
    <strong>{{ $item->client->invoice }}</strong>
  </td>
  ...
@endforeach

Remove the getInvoiceAttribute method from the Client Model

  • Related