Lets say I have three models - Artbook, Collection, Artwork with relationship as follows
Artbook -> hasMany -> Collection -> hasMany -> Artwork
Artbook -> hasMany -> Artwork -> through -> Collection
----------------------------------
Artbook is a public model while Collection belongs to a user. So any user can create a Collection for any Artbook. Thus, the user relation is as:
User -> hasMany -> Collection
User -> hasMany -> Artwork -> through -> Collection
Note: Collection has an added_by column that contains the user's id. I have no idea why the previous developer didn't just use user_id instead.
----------------------------------
Now I have a page where I display all Artbooks a user has contributed to. Here, I need to sort the Artbooks by latest image uploaded by that user in that Artbook. The image may be in a new Collection or an existing one.
How do I achieve this? I've having a hard time querying the Artbook model in such a manner.
This is my current query for retrieving Artbooks (default sorting)
$artbooks = Artbook::whereHas('collection', function ($query) use ($request) {
$query->whereAddedBy($request->user()->id);
})->withCount(['artwork' => function ($query) {
return $query->whereHas('collection', function ($q) {
return $q->whereAddedBy(request()->user()->id);
});
}])->withFilters()->paginate($request->perPage ?: 20);
return ArtbookResource::collection($artbooks );
I want to add an orderBy clause in the above query that orders it by latest image in each artbook for a user.