我进行了查询,并得到了11个db对象数组的集合。基本上是11个帖子。如果这些帖子(标题,模型或说明中)中存在字符串,则需要进行通配符搜索。如何最好地实现呢?我尝试使用多个orWhere,但似乎无法正常工作。
我的功能
public function search(Request $request)
{
$this->validate($request, [
'search' => 'required',
'country' => 'required',
]);
$search=$request->input('search');
$posts = Country::where('country_name', $request->input('country'))->first()->posts;
$customers=$posts::where('title','LIKE','%'.$request->search.'%')
->orWhere('model','LIKE','%'.$request->search.'%')
->orWhere('notes','LIKE','%'.$request->search.'%')
->orWhere('description','LIKE','%'.$request->search.'%')
->get();
dd($posts);
}
$ posts-响应
Collection {#367 ▼
#items: array:11 [▼
0 => Post {#368 ▼
#table: "posts"
#dates: array:1 [▶]
#fillable: array:18 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:22 [▼
"id" => 1
"title" => "Brand New Harley Davidson For Sale"
"make_id" => "1"
"model" => "Sportster"
"year" => 2019
"price" => "987890.00"
"mileage" => 8798
"mileage_unit" => "KM"
"negotiable" => "negotiable"
"condition" => "All Good"
"plate" => null
"vin" => null
"color" => null
"notes" => null
"description" => null
"created_by" => 1
"status_change" => "2019-06-12 02:35:51"
"status" => "Deleted"
"slug" => "1560305498-Brand-New-Harley-Davidson-For-Sale"
"created_at" => "2019-06-12 02:11:38"
"updated_at" => "2019-06-12 02:36:50"
"laravel_through_key" => "IND"
]
#original: array:22 [▶]
#changes: []
#casts: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => Post {#369 ▶}
2 => Post {#370 ▶}
3 => Post {#371 ▶}
4 => Post {#372 ▶}
5 => Post {#373 ▶}
6 => Post {#374 ▶}
7 => Post {#375 ▶}
8 => Post {#376 ▶}
9 => Post {#377 ▶}
10 => Post {#378 ▶}
]
}
答案 0 :(得分:1)
$posts
是指
$posts = Country::where('country_name', $request->input('country'))->first()->posts;
其中不包括搜索查询,您应该转储$customers
来查看结果。
此外,您的$customers
查询与$posts
无关,您正在进行两个不同的查询。您当前的$posts
将返回所有国家/地区的帖子。
$posts = Country::where('country_name', $request->input('country'))->first()->posts()
->where('title','LIKE','%'.$search.'%')
->orWhere('model','LIKE','%'.$search.'%')
->orWhere('notes','LIKE','%'.$search.'%')
->orWhere('description','LIKE','%'.$search.'%')
->get();
答案 1 :(得分:0)
尝试以下查询。
$posts = Country::with(['posts' => function($oQuery) use($search){
$oQuery->where('title','LIKE','%'.$search.'%')
->orWhere('model','LIKE','%'.$search.'%')
->orWhere('notes','LIKE','%'.$search.'%')
->orWhere('description','LIKE','%'.$search.'%');}])->where('country_name', $request->input('country'))->first();