调用未定义的方法Illuminate \ Database \ Query \ Builder :: title()

时间:2017-04-10 14:44:21

标签: laravel laravel-5

我正在尝试实施搜索,以便用户可以输入图书的标题,laravel将浏览数据库并显示与任何角色匹配的结果。

我的书'表格包含一个标题'字段。

但是,如果我输入例如' f'我明白了:

  

调用未定义的方法Illuminate \ Database \ Query \ Builder :: title()

搜索刀片:

@extends('layouts.master')

@section('title')

@section('content')
    <h1>Search for books</h1>
    <form action="{{url('details')}}" method="POST">
    {{ csrf_field() }}
        <div>
            <input type='text'  name='book' placeholder='Enter any character' />
        </div>
    <input type="submit" name="submitBtn" value="Search">
    </form>
@endsection

详细信息=结果页面:

@extends('layouts.master')

@section('title')

@section('content')
    <h1>User Details</h1>
      <form>
      <p>
    <ul>
      @foreach ($books as $book)
    <a href=  "{{url('reader/'.$book->title)}}">
      {{$book->title}}</a>
      </p>
</form>
@endforeach
    </ul>
@endsection

控制器:

    function search()
    {
        $books = Book::all();
        return view('layouts/search',['books' => $books]);
    }
        function details() {
            $searchTerms = explode(' ', \Request::input('book'));
            $books = Book::whereHas('title', function($query) use($searchTerms) {
                if(!empty($searchTerms)){
                for

each($searchTerms as $book) {
               $query->where('book', 'LIKE', '%'. $book .'%');
            }          
         }
         })->first();
            return view('layouts/details', compact('book'));
}

更新::

    function search()
    {
        $books = Book::all();
        return view('layouts/search',['books' => $books]);
    }
        function details() {
            $searchTerms = explode(' ', \Request::input('book')); 
            $books = Book::where(function($q) use($searchTerms) {
            foreach ($searchTerms as $book) {
             $q->orWhere('title', '%'.$book.'%');
            }
        })->first();
        return view('layouts/details', compact('books'));
}

1 个答案:

答案 0 :(得分:0)

你不应该在这里使用whereHas(),因为它使用了你没有的关系。看起来titlebooks表中的一列,所以请改为:

$books = Book::where(function($q) use($searchTerms) {
        foreach ($searchTerms as $title) {
             $q->orWhere('title', '%'.$title.'%');
        }
    })
    ->first();

如果数组中有$searchTerms并且您只需找到第一本书,它就会有效。

此外,如果您想按完整标题搜索,可以使用whereIn()

$books = Book::whereIn('title', $searchTerms)->first();