过滤Laravel资源集合有更好的方法

时间:2019-05-01 18:09:57

标签: php laravel laravel-5

我正在尝试在Laravel中创建Restful API,并且正在利用为API输出而设计的资源功能。我创建了以下模型: 书籍,作者和类别。我还为每个模型创建了资源。

作者和书之间存在一对多关系,类别和书之间存在多对多关系,并具有数据透视表。

我可以使用以下内容轻松返回所有书籍的收藏集:

return BookResource::collection(Book::with(['author', 'categories'])->paginate(10));

但是我想按作者和类别轻松过滤,因此我已在控制器中以以下方式实现了它:

public function index(request $request)
{
    //if no filer params are passed in return all books with author and categories
    if (!$request->has('author') && !$request->has('category')) {
        return BookResource::collection(Book::with(['author', 'categories'])->paginate(10));
    }

    //author param is passed in
    if($request->has('author') && !$request->has('category')){
        $authorName = $request->author;
        return BookResource::collection(Book::whereHas('author', function ($query) use ($authorName) {
            $query->where('name', $authorName);
        })->get());
    }

    //category param is passed in
    if(!$request->has('author') && $request->has('category')){
        $categoryName = $request->category;
        return BookResource::collection(Book::whereHas('categories', function ($query) use ($categoryName) {
            $query->where('name', $categoryName);
        })->get());
    }
}

是否有更好,更有效的方法来返回按作者和类别过滤的BookResource集合?

1 个答案:

答案 0 :(得分:0)

请尝试以这种方式实施。希望这可以帮助。谢谢。

public function index(){
$author = request ('author', null);
$category = request ('category', null);

$books = Book::with(['author', 'categories'])->when($author, function ($query) use ($author) {
 return $query->whereHas('author', function ($query) use ($author){
  $query->where('name', $author);
});
})->when($category, function ($query) use ($category) {
return $query->whereHas('categories', function ($query) use ($category) {
   $query->where('name', $category);
   });
})->paginate(10);
return BookResource::collection($books);
}