douxuanma4357 2019-05-01 18:09
浏览 81
已采纳

过滤Laravel资源集合是一种更好的方法

I am experimenting with creating a Restful API in Laravel and I am making use of the resources feature designed for API output. I have created the following models: Book, Author and Category. I also created a resource for each of these models.

There is a one to many relationship between author and book and a many to many between category and book which has a pivot table.

I can return a collection of all books easily with the following:

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

But I want to easily filter by author and category so I have implemented it in the following way inside my controller:

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

Is there a better more efficient way of returning the BookResource collection filtered by author and category?

  • 写回答

1条回答 默认 最新

  • drox90250557 2019-05-01 19:02
    关注

    Please try to implement this way. Hope this helps. Thanks.

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?