Search code examples
sqllaravellaravel-bladeeloquent-relationship

reducing the number of sql queries from the front


    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 class="text-center">
        <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 Has Many Through. Or how to solve this situation I don't need an account at the front but I need sum of amounts


Solution

  • I did so

    added invoice column to write sum of account->amounts

    Schema::table('clients', function (Blueprint $table) {
              $table->integer('invoice')->default(0);
            });
    

    after than added AccountObserver

    class AccountObserver
    {
      public function creating(Account $account)
      {
        $account->client()->increment('invoice',$account->amount);
      }
    
      public function updating(Account $account)
      {
        $account->client()->increment('invoice',$account->amount);
      }
    } 
    

    Controller

    $orders = Order::with(['transaction', 'client', 'delivery', 'address'])
      ->latest()->paginate(50);
    return view('admin.order.index', compact('orders'));
    
    View
    <td class="text-center">
        <strong >{{$item->client->invoice}}</strong>
    </td>
    

    enter image description here