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.