我正在使用PHP Fractal库来处理我的Laravel API响应。我的模型是Post
,其中包含许多Comments
。我想要做的是让所有帖子按照过去X天收到的评论数量排序。基本上这个API调用:
GET /api/posts?include=comment_count:since_days(7)&sort=comment_count:desc`
因此我使用PostTransformer
来解析include参数,并在请求包含此参数时添加原始资源:
class PostTransformer extends TransformerAbstract
{
// ...
public function includeCommentCount(Post $post, ParamBag $params = null)
{
$sinceDays = // ... extract from ParamBag
$commentCount = $post->getCommentCountAttribute($sinceDays);
return $this->primitive($commentCount);
}
}
包含工作正常,允许指定Fractal库中的since_days
参数。但是,我现在不确定如何对帖子进行排序。这是我的PostController
:
class PostController extends Controller
{
// ...
public function index(Request $request)
{
$orderCol, $orderBy = // ... parse the sort parameter of the request
// can't sort by comment_count here, as it is added later by the transformer
$paginator = Post::orderBy($orderCol, $orderBy)->paginate(20);
$posts = $paginator->getCollection();
// can't sort by comment_count here either, as Fractal doesn't allow sorting resources
return fractal()
->collection($posts, new PostTransformer())
->parseIncludes(['comment_count'])
->paginateWith(new IlluminatePaginatorAdapter($paginator))
->toArray();
}
}
这个问题有解决方法吗?