如何将多列合并为一个?拉拉韦尔

时间:2018-11-19 03:28:49

标签: php html sql laravel

这是我的控制者:

//initiate
var filterAResultArr= [];
var filterBResultArr= [];
var filterCResultArr = [];
var filterDResultArr= [];
var filterSeResult = [];

路线:

public function search(request $request)
{
    $request->flash();
    $search = $request->get('q');
    $vehicles = vehicle::where('make', 'LIKE', '%'.$search. '%')
                ->orWhere ( 'model', 'LIKE', '%' . $search . '%' )
                ->orWhere ( 'year', 'LIKE', '%' . $search . '%' )
                ->paginate(9);
    return view('user.vehicles.vehicles',compact('vehicles'));
}

Laravel剑

Route::get('/vehicles/search', 'VehiclesController@search');

问题

当我搜索ex:<form action="/vehicles/search" method="get"> <div class="row"> <div class="col-md-12 my-1"> <div class="input-group"> <input type="text" class="form-control" name="q" value="{{ old('q')}}" autocomplete="off" placeholder="Search for brand, model, year, etc"> <span class="input-group-btn"> <button class="btn btn-success" type="submit"><span class="fa fa-search"></span></button> </span> </div> </div> </div> <form> 时,由于

Toyota

但是当我搜索where('make', 'LIKE', '%'.$search. '%') 时,没有结果。

我想要的是:当我搜索Toyota Innova 2013时,代码应显示Toyota Innova 2013makemodel的所有结果

3 个答案:

答案 0 :(得分:0)

尝试一下:

$vehicles = vehicle::where(function($query) use ($search) {
    $parts = explode(' ', $search);
    foreach ($parts as $part) {
        $query = $query->where('make', 'LIKE', '%'.$part. '%')
            ->orWhere ( 'model', 'LIKE', '%' . $part. '%' )
            ->orWhere ( 'year', 'LIKE', '%' . $part. '%' )
    }
})

我还没有测试过,但是它应该将搜索查询中的每个单词与每一列进行比较

答案 1 :(得分:0)

您必须以一种形式根据列来制作三个搜索按钮。

您正在使用$search从控制器传递三个参数。

在您的模型中尝试一下:

第一列

 if ($request->make != null && $request->make != '') {
     $data->where('vehicle.make', $request->make);
 }

第二列

 if (isset($request->model) && $request->model != '') {
     $data = $data->where('vehicle.model', $request->model);
 }

第三列

 if (isset($request->year) && $request->year != '') {
     $data = $data->where('vehicle.year', $request->year);
 }

答案 2 :(得分:0)

我使用db :: raw和concat
laravel doc

use DB;

public function search(request $request)
     {
      $request->flash();
      $search = $request->get('q');
      $vehicles = vehicle::where(\DB::raw("CONCAT_WS(' ', make, model, year)"), 'LIKE', '%' . $search . '%')
      ->paginate(9);
      return view('user.vehicles.vehicles',compact('vehicles','vehicless'));
    }