Laravel 在两个表中搜索“LIKE”查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28552765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:57:20  来源:igfitidea点击:

Laravel search 'LIKE' query in two tables

phpsqlsearchlaraveleloquent

提问by Robert M. Tijerina

I'm currently trying to set up a search bar that filters the results of two tables, booksand categories.

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

I have setup relationships for both models where:

我为两个模型设置了关系,其中:

Book.php (Model) (table: id, b_name, b_author, cat_id)

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

public function bookCategory()
{
  return $this->belongsTo('Category', 'cat_id', 'id');
}

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

Category.php(模型)(表:id,cat_name)

public function book()
{
  return $this->hasMany('Book', 'cat_id', 'id');
}

BookController.php

图书控制器.php

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

  return Response::json($books);
}

But obviously this won't work. The reason I'm doing this is because I want to allow users to use the same search bar to filter different columns (which I know how to do it in one table, but not two or more).

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

回答by vitalik_74

You can use that.

你可以用那个。

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

})->get();

See more in http://laravel.com/docs/4.2/eloquent#querying-relations

http://laravel.com/docs/4.2/eloquent#querying-relations 中查看更多信息

EDIT:

编辑:

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

    })->get();

You get cat_namefrom relation.

cat_name从关系中得到。