我正在尝试使用搜索字段的用户输入值来查询数据库。
但我得到的结果是完全错误的。它没有搜索词。
我不知道我哪里可能做错了。我遵循了laravel doc
,以及一些关于stackoverflow
的问题,但似乎没有任何效果。
任何人都可以检查我的查询,也许可以引导我走向正确的方向。
我的查询就像这样 Query
术语是 Rose
,并且只有一条记录具有标题名称 Rose
public function catelogSearch(Request $request){
if ($request->has('query') && $request->get('query')!= ''){
$searchQuery = $request->get('query');
$query = ProductCategory::with(['product'=>function($q) use($searchQuery){
$q->where([
['product_type','both'],
['title','LIKE','%'.$searchQuery.'%'],
]);
if(request()->segment(1)=='shopping'){
$q->orWhere('product_type','shop');
}elseif (request()->segment(1)=='subscription'){
$q->orWhere('product_type','sub');
}
$q->whereHas('price',function ($q){
$q->where('quantity','>',0);
$q->where('status',1);
});
}])->with('product');
$data['result']=$query->paginate(30)->toArray();
print_r($data);
}
此查询为我提供了数据库中的所有数据,这与它应该为我提供标题中包含查询词的位置不同。另请注意,我正在查询 with('product')
两次。如果我这样做一次,它不会返回产品数据,而是返回产品的空响应。
任何人都可以建议我吗? 谢谢你。
网址: localhost:8000/shopping/catalogsearch/result?query=rose
模型关系 ProductCategory.php
public function product()
{
return $this->belongsTo('App\Models\Product');
}
产品.php
public function price(){
return $this->hasMany('App\Models\ProductPrice');
}
产品类别表
-----------------------------------------------
id | product_id| category_id | sub_category_id |
-----------------------------------------------
产品表
----------------------------
id | title | slug | product_type |
-----------------------------
产品价格表
----------------------------
id | product_id| price| quantity |
-----------------------------
最佳答案
public function catelogSearch(Request $request){
if ($request->has('query')){
$searchQuery = $request->get('query');
$query = ProductCategory::product;
$query = $query->where('title', 'LIKE', '%'.$searchQuery.'%');
if(request()->segment(1)=='shopping'){
$query = $query->where('product_type','shop');
}elseif (request()->segment(1)=='subscription'){
$query = $query->where('product_type','sub');
}else{
$query = $query->whereIn('product_type',array('shop','sub'));
}
$query = $query->price->where('quantity','>',0)
->where('status',1)->get();
dd($query);
}
}
我已经删除了这些代码,一旦您获得上述代码的所需输出,我将在稍后添加它。所以请尝试让我知道输出。
if(request()->segment(1)=='shopping'){
$q->orWhere('product_type','shop');
}elseif (request()->segment(1)=='subscription'){
$q->orWhere('product_type','sub');
}
关于mysql - Laravel Eloquent 模式搜索无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49575816/