使用 Laravel 中的标签进行搜索

Search using Tags in Laravel

我对 Laravel 和

很陌生

尝试通过标签创建一个搜索系统,比如我有一个 products table 并且每个产品在 product_tags table 中都有多个标签。 product_tags table 有两列 product_idproduct_tag

        $search = $req->get('search'); // Input from user 
        
        $products = Product::with(['images', 'tags'])
        ->where('id', 'LIKE' , '%'.$search.'%')
        ->orWhere('product_name', 'LIKE' , '%'.$search.'%')
        ->orWhere('product_price', 'LIKE' , '%'.$search.'%')
        ->get();

        dd($products);

产品模式

class Product extends Model
{
    use HasFactory;

    public function images()
    {
        return $this->hasMany(ProductImage::class, 'product_id', 'id')->orderBy('id', 'desc');
    }
    public function tags()
    {
        return $this->hasMany(ProductTag::class, 'product_id', 'id')->orderBy('id', 'desc');
    }
}

Product::with(['images', 'tags'])
    ->where(function ($query) use ($search) {
        $query->where('id', 'LIKE' , '%'.$search.'%')
              ->orWhere('product_name', 'LIKE' , '%'.$search.'%')
              ->orWhere('product_price', 'LIKE' , '%'.$search.'%');
    })
    ->orWhereHas('tags', function ($query) use ($search) {
        $query->where('product_tag', 'LIKE', '%'.$search.'%');
    })
    ->get();