Description
Story time
When requesting the relation of an endpoint i.e: /api/v1/companies/1/users
i get a list of users within the company of ID 1, true.
Now let's say I want to include some "likes" for each user, so we add that as a query parameter: /app/v1/companies/1/users?include=stars
. Now we get a list of users, and all their stars have been included in the response as well, true.
Problem time
Let's say I want to be more specific, and only get 5 stars per user included. How would I go around solving this?
- If there are 3 users we should get 5 stars for each of them, totaling at 15 stars
- If one of the users only has 2 stars those are still included and the other two users will still have their 5 stars. Giving a total of 12 stars being included.
First try
In the App\Models\User eloquent model of mine i just cold heartedly added a limit onto the query:
public function stars()
{
return $this->hasMany(Stars::class)->limit(5);
}
But this resulted in there only being returned 5 stars in total.
Where to go next
I am trying to dig deeper how loading of included models works, but I am having a hard time navigating around and finding the source where the final query is constructed.
It does seem a bit naughty to me that the stars relationship shares its limit globally, since it should only limit the amount of stars for that one user instance, right? I would understand if the relation method was static and therefore would apply to the entire collection of users.
Am I missing something, a filter or something that actually lets me do exactly this? Looking forward to hearing from you @lindyhopchris :)