【发布时间】:2021-01-13 15:12:14
【问题描述】:
我有问题。
我正在做一个搜索功能,用户将通过表单输入他们想要搜索的产品并返回产品。
这是表格。
<form action="{{ route('shopAll') }}">
<input type="text" name="search" placeholder="Search Products...">
<button type="submit"><i class="ti-search"></i></button>
</form>
产品.php
class Product extends Model{
protected $fillable = [
'name','added_by', 'user_id', 'category_id', 'subcategory_id', 'subsubcategory_id', 'brand_id', 'video_provider', 'video_link', 'unit_price',
'purchase_price', 'unit', 'slug', 'colors', 'choice_options', 'variations', 'current_stock'
];
public function category(){
return $this->belongsTo(Category::class);
}
public function subcategory(){
return $this->belongsTo(SubCategory::class);
}
public function subsubcategory(){
return $this->belongsTo(SubSubCategory::class);
}
public function brand(){
return $this->belongsTo(Brand::class);
}
}
SearchController.php
if($request->search){
$data['products'] =
Product::where('name', 'LIKE', '%' . $request->search . '%')
->orWhere('tags', 'LIKE', '%' . $request->search . '%')
->orWhere('meta_title', 'LIKE', '%' . $request->search . '%')
->orWhere('slug', 'LIKE', '%' . $request->search . '%')
->get();
} else {
$data['products'] = Product::paginate(20);
}
return view('frontend.shop-all', $data);
我想让查询在类别、子类别、子子类别和品牌中包含“orWhere”,这样当用户想要搜索产品时,他们可以搜索品牌或与产品相关的任何属性。有人可以帮我解决这个问题吗?
非常感谢。
【问题讨论】:
-
这是一个非常不幸的结构,将成为维护/升级的皮塔。您应该考虑类别的邻接列表或嵌套列表。已经有一些包利用了这种请求。例如检查laravel-categories by rinvex。它不会限制为两个级别的子级,并且会为您提供更好的功能抽象。