skip to Main Content
      
  $suppliers = Supplier::with(
            [
                'purcheses' => function ($query) {
                    $query->with(
                        [
                            'payments' => function ($query) {
                                $query->sum('amount');
                            }
                        ]
                    )->get();
                }
            ]
        )->latest()->get();

I have a suppliers table with has-many relations with purchases of purchases table with has-many relations with payments and payment belongs to purchases, how to get the total sum of payment for each purchase that belongs to this supplier?

2

Answers


  1. I think this package might help you,

    The package’s readme illustrates various types of relationships that this package supports:

    • HasMany

    • ManyToMany

    • MorphMany

    • MorphToMany

    • MorphedByMany

    • BelongsTo

    Here’s an example from the readme of a HasMany relationship for a complex relationship:

    /*
     Country
       -> has many
     User
       -> has many
     Post
       -> has many
     Comment
    */
     
    class Country extends Model
    {
        use StaudenmeirEloquentHasManyDeepHasRelationships;
     
        public function comments()
        {
            return $this->hasManyDeep('AppComment', ['AppUser', 'AppPost']);
        }
    }
     
    // Access country comments
    $country->comments();
    

    In the above example, the package uses Eloquent conventions keys, and the package allows you to specify custom keys for local and foreign keys.

    Login or Signup to reply.
  2. You might want to try flatMap and loadSum:

    $suppliers = Supplier::with('purchases')
        ->get();
    
    // Load the payments total for each purchase.
    $suppliers
        ->flatMap
        ->purchases
        ->loadSum('payments', 'amount');
    
    return $suppliers;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search