【问题标题】:Filtering Laravel resource collections is there a better way过滤 Laravel 资源集合有没有更好的方法
【发布时间】:2019-05-01 18:09:56
【问题描述】:

我正在尝试在 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 集合?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多