eskimo
eskimo

Reputation: 2624

Laravel get sum in polymorphic many to many

I'd like to get the sum of a column of a polymorphic many to many relationship. So let's say you have a Post and a Comment model with that relationship, this doesn't work:

$posts = Post::withCount([
  'comments as comments_priority_sum' => function ($q) {
    $q->sum('comments.priority');
  },
  ])
  ->orderBy('title', 'asc')
  ->get();

Upvotes: 1

Views: 359

Answers (1)

porloscerros Ψ
porloscerros Ψ

Reputation: 5088

As of laravel 8.x, we also have the withSum() method, so you could simply do:

Post::withSum('comments', 'priority')->get();

And you would get a comments_sum_priority field in each instance of the Post model.


For older versions you can use a raw expression:

Post::withCount(['comments as comments_sum_priority' => function($query) {     
    $query->select(DB::raw('sum(priority)')); 
}])->get()

Just to clarify, your query doesn't work because the query builder's sum aggregate executes the query.

Upvotes: 1

Related Questions