dimanche 29 avril 2018

Sort a resource collection in Fractal by an included primitive

I'm using the PHP Fractal library for my Laravel API responses. My model is a Post that has many Comments. What I want to do is to get all posts sorted by the amount of comments it has received in the last X days. Basically this API call:

GET /api/posts?include=comment_count:since_days(7)&sort=comment_count:desc`

Therefor I'm using a PostTransformer that parses the include parameter and adds a primitive resource if this include is requested:

class PostTransformer extends TransformerAbstract 
{

  // ...

  public function includeCommentCount(Post $post, ParamBag $params = null) 
  {
    $sinceDays = // ... extract from ParamBag

    $commentCount = $post->getCommentCountAttribute($sinceDays);

    return $this->primitive($commentCount);
  }
}

The include is working fine and allows to specify the since_days parameters as it is intended in the Fractal library. However, I'm not sure on how to sort the posts now. This is my 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();
  }
}

Is there a solution to this problem?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire