DEV Community

JohnDivam
JohnDivam

Posted on • Edited on

2

Laravel WithSum() on hasManyThrough->where relationship

In Laravel, we can use the withSum method with combination hasManyThrough relationship with the where clause to calculate the sum of related records from while applying conditions to the related records. Here's how you can do it:

Assuming you have the same example of Client, Order, OrderDetail models where you want to calculate the sum of qnt in OrderDetail populations for a specific client but with additional conditions :

// Order.php model
class Order extends Model
{
     protected $fillable = [
        'user_id',
        'status',
     ];
}

// OrderDetail .php model
class OrderDetail extends Model
{
     protected $fillable = [
        'order_id',
        'product_id',
        'quantity',
        'amount'
     ];
}


Enter fullscreen mode Exit fullscreen mode

Now, define the hasManyThrough relationship in the Client model:


// Client.php model
class Client extends Model
{
      public function ordersDetails(){
        return $this->hasManyThrough(OrderDetail::class,Order::class,'user_id','order_id','id','id')
       ->where('orders.status',Order::COMPLETED);
    }
}
Enter fullscreen mode Exit fullscreen mode

To calculate the sum of quantity for a specific clients, you can use the withSum method in your query:

  $clients = Client::withSum(['ordersDetails'],'quantity')->get();
   // you can see column order_details_sum_quantity 

Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay