mysql - 如何在 Laravel 中获取相似的产品标签?

标签 mysql laravel laravel-5

我有产品表,每个产品都有以这种方式存储的标签

“标签1,标签2,标签3”(字符串)

现在,当我显示产品时 - 我想显示所有具有与当前产品相关的标签的产品

例如

product1 -> tags (tag1,tag2,tag3)
product2 -> tags (tag3,tag4,tag5)
product3 -> tags (tag4,tag5,tag6)

例如在产品 1 中 -> 它应该捕获产品 2,因为它具有相同的标签 (tag3)

不幸的是我没有编写任何代码 - 我不知道如何实现它

最佳答案

是的,你可以通过艰难的方式实现这一目标。如果您的数据库良好,它将有助于实现任何类型的搜索。您可以创建两个表

1) Products (column :- id, name) 2) product_tags(column :- id, product_id, tag_name)

使用此结构,您可以获取任何类型的产品。

如果您不想使用上述部分,请根据您的要求尝试此操作。现在我假设您在产品表中有三个记录,如下所示:-

ID product_name  product_tags
1   product1       tag1,tag2,tag3
2   product2       tag3,tag4,tag5
3   product3       tag4,tag5,tag6

现在,根据您的要求,您在网页中显示 Product1,并且可能会显示类似的标签产品。 所以你的逻辑将是这样的:-

$productDetail = Product:where('product_name','product1')->first();  // this query will return tags of `product1`
 $productDetail = json_decode(json_encode($productDetail),true); //convert to array
if(!empty($productDetail)){
   $producttags = explode(',',$productDetail['product_tags']);
   $productids = array();
   foreach($producttags as $tag){
       $getproducts = Product::whereRaw("find_in_set($tag,product_tags)")->get();
      $getproducts= json_decode(json_encode($getproducts),true);
      if(!empty($getproducts)){
          foreach($getproducts as $product){
               $productids[] = $product['id'];
           }
       }
    }
   $productids = array_unique($productids);
  }
  echo "<pre>"; print_r($productids); // print the productids here and after that use `whereIn` for fetcch tag product ids

希望对您有帮助!祝您的项目好运

关于mysql - 如何在 Laravel 中获取相似的产品标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917627/

相关文章:

php - Mysql 加入,需要帮助格式化查询

php - 是否可以在App :before filter in Laravel?中返回

php - Laravel Eloquent 更新列使用关系列

MySQL 选择多个值并添加到一列

php - 这可以在 MySQL 查询中完成,还是需要在 PHP 中完成? (服务器端)

php - SQL 注入(inject)漏洞神奇地 self 修复?

php - Laravel 上一个和下一个记录

Laravel 更新不起作用告诉 _method 未知列

javascript - 如何在Vue.js中设置自定义中间件

php - 一对多关系查询