I have a polymorphic relationship (requests - requestable) which I want to do an order by the morph class.
Here is what my current implementation looks like:
// Model: Request
// Table: requests
// Morph: requestable_type, requestable_id
public function requestable()
{
return $this->morphTo();
}
// Model: MaintenanceRequest
// Table: maintenance_requests
public function request()
{
return $this->morphOne(Request::class, 'requestable');
}
// Model: HousekeepingRequest
// Table: housekeeping_requests
public function request()
{
return $this->morphOne(Request::class, 'requestable');
}
Both the maintenance request and housekeeping request has a column named ticket. So when querying, how can I order by the requestable relationships ticket?
What I have tried:
$query = $this->model->newQuery(); // model being Request
$query->with(['requestable' => function($q) {
$q->orderBy('ticket', 'desc'); // asc or desc comes from SPA
}]);
This does not seem to work. I am not sure how a join on this would look like since I want to order by all requestable classes instead of one specific class. What I mean is I don't want to run the order by for specifically MaintenanceRequest or HousekeepingRequest but can I do order by the ticket for both the models? If so, what is the approach?