Laravel在两个表中搜索"LIKE"查询

Rob*_*ina 4 php sql search laravel eloquent

我目前正在尝试设置一个搜索栏,用于过滤两个表格,书籍类别的结果.

我有两个模型的设置关系,其中:

Book.php(模型)(表:id,b_name,b_author,cat_id)

public function bookCategory()
{
  return $this->belongsTo('Category', 'cat_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)

Category.php(Model)(表:id,cat_name)

public function book()
{
  return $this->hasMany('Book', 'cat_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)

BookController.php

public function getFilterBooks($input)
{
  $books = Book::with('bookCategory')->where('**cat_name at category table**. 'LIKE', '%' . $input . '%'')->get();

  return Response::json($books);
}
Run Code Online (Sandbox Code Playgroud)

但显然这不起作用.我这样做的原因是因为我想允许用户使用相同的搜索栏来过滤不同的列(我知道如何在一个表中执行此操作,但不是两个或更多).

vit*_*_74 9

你可以用它.

Book::whereHas('bookCategory', function($q) use ($input)
{
    $q->where('cat_name', 'like', '%'.$input.'%');

})->get();
Run Code Online (Sandbox Code Playgroud)

请参阅http://laravel.com/docs/4.2/eloquent#querying-relations中的更多内容

编辑:

Book::with('bookCategory')->whereHas('bookCategory', function($q) use ($input)
    {
        $q->where('cat_name', 'like', '%'.$input.'%');

    })->get();
Run Code Online (Sandbox Code Playgroud)

你得到cat_name了关系.