我想在Laravel Controller中实现Eloquent Search,这是mysql 中的示例查询
SELECT * FROM trx_order_ecommerce WHERE city LIKE '%Depok%' OR city LIKE '%Bogor%'
我使用POST方法检索城市数据,
array:3 [▼
0 => "Depok"
1 => "Bogor"
2=> ,....
]
这是我的控制器中的代码
$data = DataOrderEcommerce::orderBy('created_at','desc');
if(isset($request->city_name))
{
$dat = $request->city_name;
for ($i=0; $i < count($dat) ; $i++) {
if($i=0){
$data->Where('city', 'like', '%'.$dat[$i]. '%' );
}
elseif($i>0){
$data->OrWhere('city', 'like', '%'.$dat[$i]. '%' );
}
else{
}
}
$data->get()
}
但我没有得到任何数据,。。
这样尝试:
$query = DataOrderEcommerce::query();
if($request->has('city_name'))
{
$query->whereIn('city', $request->city_name);
}
$query->orderBy('created_at','desc')->get();
尝试这种方法:
$data = DataOrderEcommerce::orderByDesc('created_at')
->when($request->has('city_name'), function($q) use ($request)
{
foreach($request->city_name as $key => $city) {
if ($key == 0) {
$q->where('city', 'like', '%'.$city. '%' );
} else {
$q->orWhere('city', 'like', '%'.$city. '%' );
}
}
})->get();