1

I have a total_views attribute added to my Product model like this

public function getTotalViewsAttribute(){

  return (int)$this->views()->sum('count');

}

views() is a relationship on Product like this

public function views()
{
        return $this->morphMany(View::class, 'viewable');
}

What I would like to do is order my Product by the total_views. Or in other words to order by the sum of the views() relationship.

I have tries to ->orderBy('total_views') on the query but it doesn't seem to work as expected.

Any help will be highly appreciated.

Kha Kali
  • 169
  • 2
  • 13

1 Answers1

0

Eloquent getter can only work, when the query has been executed, therefor your current code is not working. I would always use withCount(), on the query;

$products = Product ::withCount(['views'])->get();

The count would be on a property named views_count;.

foreach ($products as $product) {
    $product->views_count; // get view count
}

And also possible to order by the column, as it will be present in the SQL returned by the query.

Product ::withCount(['views'])->orderBy('views_count', 'desc')->get();
mrhn
  • 17,961
  • 4
  • 27
  • 46