Eloquent where条件AND(条件OR条件OR条件)



有人能告诉我我做错了什么吗?我想获取所有状态为0的项目,以及是否有任何数据匹配。我的代码就像这个

public function search(Request $request){
if($request->has('q')){

$search_query = $request->input('q');
$projects = Project::where(['status' => '0'])->get();
$projects = $projects->where(function($query) use ($search_query) {
$query->where('title','LIKE','%'.$search_query.'%')
->orWhere('shortDescription','LIKE','%'.$search_query.'%')
->orWhere('longDescription','LIKE','%'.$search_query.'%')
->orWhere('tags','LIKE','%'.$search_query.'%')
->orWhere('projectLink','LIKE','%'.$search_query.'%');
});
$projects->get();
dd($projects);
}
}

我收到这个错误

ErrorException
explode((要求参数2为字符串,对象给定

我解决了这个问题,但对代码做了一些更改。。。如果你喜欢,就拿去吧!我测试了一下,它起作用了。

if($request->has('q')){
// Your $request->q Value
$term = $request->q;
$projects = DB::table('tbl_projects')->where('status', '=', 0) 
->where(function ($query) use ($term) {
$query->where('title', 'LIKE', '%'.$term.'%')
->orWhere('shortDescription', 'LIKE', '%'.$term.'%')
->orWhere('longDescription', 'LIKE', '%'.$term.'%')
->orWhere('tags', 'LIKE', '%'.$term.'%')
->orWhere('projectLink', 'LIKE', '%'.$term.'%');
})
->get();
//dd($projects);
}

原始查询是:

select * from `tbl_projects` where `status` = 0 and (`title` LIKE %bla bla% or `shortDescription` LIKE %bla bla% or `longDescription` LIKE %bla bla% or `tags` LIKE %bla bla% or `projectLink` LIKE %bla bla%))

问候!

您的错误是

$projects = Project::where(['status' => '0'])->get();
  1. ("状态"=>"0"](所需子句参数不同。您必须使用("状态"、"0"(
  2. 当您使用->get((时,您有一个Collection或EloquentCollection对象。您需要一个QueryBuilder

尝试实现更好的编程逻辑。

更好的实现是

public function search(Request $request){
if($request->has('q')){
// Add array with field coincidences target. Is better if this array is a const static field in the Project model
$searchFields = ['title', 'shortDescription', 'longDescription', 'tags', 'projectLink' ]; 
// Now you can add 100 fields for search coincidences easily
$search_query = $request->input('q');
$projects = Project::where('status', '0');
foreach($searchFields as $searchField){
if ($searchField == 'title'){
$projects = $projects->where($searchField,'LIKE',"%$search_query%");
continue;
}
$projects = $projects->orWhere($searchField,'LIKE',"%$search_query%");
}
$projects = $projects->get();
dd($projects);
}
}

相关内容

  • 没有找到相关文章

最新更新