我想为我的网站创建一个高级搜索。
我的类别与书籍有很多关系(我的主要模特)
如何通过表格中的选择
来搜索类别我在控制器中的代码
public function advancedSearch(Request $request){
$book = Book::query();
if($request->get('name')){
$name = $request->get('name');
$book->where('name', 'like', '%'.$name.'%');
}
if($request->get('author')){
$author = $request->get('author');
$book->where('author', 'like', '%'.$author.'%');
}
if($request->get('category')){
// MY QUESTION
}
$books = $book->get();
$category = Category::lists('name','id');
return view('search')->with('book',$books)->with('title','Search')->with('category',$category);
}
我的表格是
{!! Form::open(['method' => 'get' , 'url' => '/search/advanced']) !!}
<div class="form-group col-md-3">
{!! Form::text('name',Input::old('name'),['class' => 'form-control input-sm col-md-3','placeholder'=>'Name']) !!}
</div>
<div class="form-group col-md-3">
{!! Form::text('author',Input::old('author'),['class' => 'form-control input-sm col-md-3','placeholder'=>'Author']) !!}
</div>
<div class="form-group col-md-3">
{!! Form::select('category[]',$category,'Select Category',['class' => 'form-control selectpicker input-sm col-md-3','placeholder'=>'Author','multiple']) !!}
</div>
<input class="btn btn-default" type="submit" name="btn" value="search">
{!! Form::close() !!}
答案 0 :(得分:3)
假设您的关系名称为categories
if($request->get('category')){
$book->whereHas('categories', function($query) use($request) {
$query->whereIn('id', $request->get('category');
});
}