我将 PHP Fractal 库用于我的 Laravel API 响应。我的模型是一个Post
有很多Comments
. 我想要做的是让所有帖子按过去 X 天收到的评论数量排序。基本上这个 API 调用:
GET /api/posts?include=comment_count:since_days(7)&sort=comment_count:desc`
因此,我正在使用PostTransformer
解析包含参数并在请求此包含时添加原始资源的 a:
class PostTransformer extends TransformerAbstract
{
// ...
public function includeCommentCount(Post $post, ParamBag $params = null)
{
$sinceDays = // ... extract from ParamBag
$commentCount = $post->getCommentCountAttribute($sinceDays);
return $this->primitive($commentCount);
}
}
包含工作正常,并允许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();
}
}
这个问题有解决方案吗?