简体   繁体   English

Laravel Eloquent 请求获取大多数类别相同的产品

[英]Laravel Eloquent request to get products with most categories in common

Each Product can have several Category每个Product可以有多个Category

On each product page, I need to display 10 "related products".在每个产品页面上,我需要显示 10 个“相关产品”。

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:为此,我想在Product模型上创建一个函数,该函数将返回具有最多共同Category其他产品,如下所示:

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.但这只会给我前 10 个至少有一个共同类别的产品。

How can I get the 10 products that have the highest number of categories in common in decreasing order?如何按降序获得共有类别数量最多的 10 个产品?

The closest I got was this in the internal query:我在内部查询中得到的最接近的是这个:

  $query->whereIn('id',$this->category_ids)
  ->orderByRaw('COUNT(id) desc');

Which isn't working.哪个不起作用。

You could try the following你可以试试下面的

  1. Group categories by product id and get count where category ids are in the product's category ids按产品 id 对类别进行分组,并计算类别 id 在产品类别 id 中的位置
  2. Order by the count in descending按降序排列

This will probably require some joins and since table structure is not shown, I can't give any proper code.这可能需要一些连接,并且由于未显示表结构,我无法提供任何正确的代码。 But hope this gives you an idea on how to do it.但希望这能让你知道如何去做。

I found a solution that works, since it's not a relationship I'll put it in a Trait and not in the Product Model, I am sure there is a better solution but here is mine anyway:我找到了一个有效的解决方案,因为它不是一种关系,我会把它放在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM