【问题标题】:Advanced search with many to many relationship in laravellaravel中具有多对多关系的高级搜索
【发布时间】:2016-01-01 19:21:40
【问题描述】:

我想为我的网站创建高级搜索。

我的类别与书籍有多对多关系(我的主要模型)

如何通过表单中的选择来搜索类别

我在控制器中的代码

 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() !!}

【问题讨论】:

  • 书籍和分类有什么关系
  • @chanafdo 它的多对多

标签: php laravel search relationship


【解决方案1】:

假设您的关系名称是categories,请尝试以下操作

if($request->get('category')){
    $book->whereHas('categories', function($query) use($request) {
        $query->whereIn('id', $request->get('category');
    }); 
}

【讨论】:

  • @chanafdo 如果我还想检查每个 id 的 colum active 怎么办?(其中 id = 10 和 active = 1)以及在哪里(id = 9 和 active = 1)你能告诉我吗我该怎么做谢谢...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 2015-10-29
  • 2021-10-18
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多