4 years ago

Multiple models to same table

Posted 4 years ago by joruro


I am doing some experiments with my project's database and I came across with a tricky problem. Think that I have a table called "vehicles" where I can different types of vehicles like cars, motorcycles or trucks. Eloquent expects a single model capable of managing this table. However, in this case, I would like to have a Model for each type of vehicle which would extend the VehicleModel. For singles queries to DB where I want a specific type of vehicle I don't see any problem. For example, I can load a CarModel from DB with this call:


Unfortunately, when I need to fetch all the items, I have to use the parent class, i.e., the VehicleModel.


This returns a collection of VehicleModels. I would like to have a collection of CarModels, MotorcycleModels and TruckModels. How can I do this? Does the Eloquent reserve any solution like some kind of factory pattern to this?

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