【问题标题】:Search using Tags in Laravel在 Laravel 中使用标签进行搜索
【发布时间】:2021-05-23 12:48:15
【问题描述】:

我是 Laravel 的新手,并且

试图通过标签建立一个搜索系统,比如我有一个products 表,每个产品在product_tags 表中有多个标签。 product_tags 表有两列 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');
    }
}

【问题讨论】:

  • 所以您希望能够搜索产品或标签?您要搜索的“标签”字段的名称是什么?

标签: laravel laravel-relations


【解决方案1】:
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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多