Filter many-to-many relationship
Hi!
I have 3 models: Gantry, Sign and Status. There are following relationship: one-to-many between Gantry and Sign and many-to-many between Sign and Status. I've got 4 tables for this: gantry, sign, sign_status (pivot) and status. In pivot table - sign_status - there is except of sign and status id - timestamp, so I can get information about what time did some status occur on a sign.
I would like to make an eloquent query to get all Gantries which signs have an error. I've got the code:
$gantries = $this->gantryRepository->whereHas('sign.status', function($x)
{
$x->whereIn('type', StatusType::ERRORS);
})->all();
It works good, but status gives all sign statuses, but I want the last status of each sign ordered by timestamp, desc of course.
In Sign model I've got method status:
public function status() : BelongsToMany
{
return $this->belongsToMany(Status::class)->withPivot('timestamp');
}
Is it possible to query like above for gantries, but filtering only by last sign's status - so it means - the last record from pivot ordered by timestamp, desc
Please or to participate in this conversation.