orkhanahmadov
2 years ago

How to retrieve data from multiple tables with different relations

Posted 2 years ago by orkhanahmadov

I'm building small insurance request website. There are 3 insurances model types in DB: Travel, Car, Property.

Each model has deep relations with different tables. For example, Travel model hasOne Country, also hasOne Currency. While Car model hasOne VehicleModel which is also hasOne VehicleManufacturer.

I'd like to show all insurance types on single HTML table, how can I eager load each model and retrieve data from them, then combine them and order them by created_at?

One option is to create polymorphic Insurance model with requestable morph name and morph insurance types to that table. Then retrieve data from Insurance model, order by created_at. But problem here is I cannot eager load all related models when I query Insurance model.

Insurance::with('requestable')->orderByDesc('created_at')->get(); // this works

But if I try to eager load deep relations it would fail:

// this would fail because Car and Property models do not have 'currency' relation
Insurance::with('requestable.currency')->orderByDesc('created_at')->get();


// this would also fail because Travel and Property models does not have 'vehicleModel' relation
Insurance::with('requestable.vehicleModel')->orderByDesc('created_at')->get();

How can I solve this?

Please sign in or create an account to participate in this conversation.