Each Product can have several Category
On each product page, I need to display 10 "related products".
To that end, I would like to create a function on the Product model, that would return other products that have the most Category in common, and that would go like so:
public function related_products()
{
return Product::with('categories')->whereHas('categories',function($query) {
$query->whereIn('id',$this->category_ids);
})->take(10)->get();
}
But this would only give me the first 10 products that have at least one category in common.
How can I get the 10 products that have the highest number of categories in common in decreasing order?
The closest I got was this in the internal query:
$query->whereIn('id',$this->category_ids)
->orderByRaw('COUNT(id) desc');
Which isn't working.