我目前正在尝试设置一个搜索栏来过滤两个表的结果,书籍 和类别。
我为两个模型设置了关系,其中:
Book.php(型号)(表:id、b_name、b_author、cat_id)
public function bookCategory()
{
return $this->belongsTo('Category', 'cat_id', 'id');
}
Category.php(模型)(表:id,cat_name)
public function book()
{
return $this->hasMany('Book', 'cat_id', 'id');
}
BookController.php
public function getFilterBooks($input)
{
$books = Book::with('bookCategory')->where('**cat_name at category table**. 'LIKE', '%' . $input . '%'')->get();
return Response::json($books);
}
但显然这是行不通的。我这样做的原因是因为我希望允许用户使用相同的搜索栏来过滤不同的列(我知道如何在一个表中执行此操作,但不知道如何在两个或更多表中执行此操作)。
最佳答案
你可以使用它。
Book::whereHas('bookCategory', function($q) use ($input)
{
$q->where('cat_name', 'like', '%'.$input.'%');
})->get();
查看更多信息 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();
你从关系中得到 cat_name
。
关于php - Laravel 在两个表中搜索 'LIKE' 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28552765/