[英]Laravel Eloquent request to get products with most categories in common
每個Product
可以有多個Category
在每個產品頁面上,我需要顯示 10 個“相關產品”。
為此,我想在Product
模型上創建一個函數,該函數將返回具有最多共同Category
其他產品,如下所示:
public function related_products()
{
return Product::with('categories')->whereHas('categories',function($query) {
$query->whereIn('id',$this->category_ids);
})->take(10)->get();
}
但這只會給我前 10 個至少有一個共同類別的產品。
如何按降序獲得共有類別數量最多的 10 個產品?
我在內部查詢中得到的最接近的是這個:
$query->whereIn('id',$this->category_ids)
->orderByRaw('COUNT(id) desc');
哪個不起作用。
你可以試試下面的
這可能需要一些連接,並且由於未顯示表結構,我無法提供任何正確的代碼。 但希望這能讓你知道如何去做。
我找到了一個有效的解決方案,因為它不是一種關系,我會把它放在 Trait 而不是Product
Model 中,我相信有一個更好的解決方案,但無論如何這里是我的:
$related_products = Product::where('id','!=',$base_product->id)
->withCount(['categories as common_categories_count' => function($query) use ($base_product) {
$query->whereIn('id',$base_product->category_ids);
}])->orderBy('common_categories_count','desc')->take(10)->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.