【发布时间】: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 集合?
【问题讨论】: