Amit Kumar
Amit Kumar

Reputation: 308

Polymorphic relation with multiple models and retrieving type of model holding

These are the models:

Inspection with data fields

id, 'inspector_id', 'room_id', 'housekeeper_id', 'comments', 'signature'

InspectionDetail with data fields

'checklist_id', 'inspectionable_id', 'inspectionable_type', 'inspection_id',
    'observation', 'snapshot','inspection_status','work_order','attende_on','attended_by'

here inspection_id refers to inspections.id, inspectionable_id refers to bedrooms.id or bathrooms.id or corridor.id and so on, inspection_type is the type of model which could be These model Bedroom, Bathroom, Corridor, Kitchen and many more. These all are also a model.

in my InspectionDetail What should be the snippet which will retrieve that exact model with data

Like if i say

$detail = $inspection->detail()->first();
$type = $detail->type();// this should return any one of Bedroom, Bathroom, Corridor etc.

here one inspection have multiple details and each detail has a type of (Bedroom, Bathroom, Corridor etc).

I am unable to figure out how I can obtain the type of detail object by morphing one of Bedroom, Bathroom, Corridor etc.

Upvotes: 0

Views: 50

Answers (1)

Matey
Matey

Reputation: 1210

You need to create a relationship mapping method in InspectionDetail:

public function inspectionable()
{
    return $this->morphTo('inspectionable');
}

Then you can retrieve the related object (of class Bedroom, Bathroom etc.) just like any other relationship:

$room = $detail->inspectionable;

Upvotes: 1

Related Questions