如何在laravel中获得类似的产品标签?

b91juud3  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(381)

我有产品表,每个产品都有这样存储的标签
“tag1,tag2,tag3”(字符串)
现在,当我显示一个产品时,我想显示所有与当前产品相关的标签
例如

  1. product1 -> tags (tag1,tag2,tag3)
  2. product2 -> tags (tag3,tag4,tag5)
  3. product3 -> tags (tag4,tag5,tag6)

例如,在产品1->中,它应该捕获产品2,因为它具有相同的标记(tag3)
不幸的是,我没有写任何代码-我不知道如何实现它

fumotvh3

fumotvh31#

是的,你可以用艰苦的方法来实现这一点。如果你使你的数据库良好,它将有助于实现任何类型的搜索。可以创建两个表

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

使用这种结构,您可以获取任何类型的产品。
如果您不想使用以上部分,请根据您的要求进行尝试。现在我假设products表中有三条记录follow:-

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

现在根据您的要求,您正在展示 Product1 在网页和可能是你正在显示类似的标签产品。所以你的逻辑是this:-

  1. $productDetail = Product:where('product_name','product1')->first(); // this query will return tags of `product1`
  2. $productDetail = json_decode(json_encode($productDetail),true); //convert to array
  3. if(!empty($productDetail)){
  4. $producttags = explode(',',$productDetail['product_tags']);
  5. $productids = array();
  6. foreach($producttags as $tag){
  7. $getproducts = Product::whereRaw("find_in_set($tag,product_tags)")->get();
  8. $getproducts= json_decode(json_encode($getproducts),true);
  9. if(!empty($getproducts)){
  10. foreach($getproducts as $product){
  11. $productids[] = $product['id'];
  12. }
  13. }
  14. }
  15. $productids = array_unique($productids);
  16. }
  17. echo "<pre>"; print_r($productids); // print the productids here and after that use `whereIn` for fetcch tag product ids

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

展开查看全部

相关问题