ITGuy1990
ITGuy1990

Reputation: 93

Laravel Eloquent - Multiple models for one table

I have 3 eloquent models which are pretty much te same and represent discounts:

They all will get a method called "canBeApplied(Productable $productable)". Which does have a look at the given productables and then determine if the productable will be eligible for the discount it represents. The implementation of this method is different for those 3 different Discounts.

Now, their attributes are pretty much the same. They all have these attributes: name, active, valid_from, valid_trough. So i think i would need to have one single database table with these fields / column to represent those 3 discount eloquent models:

The column discountable_type will then the the fully qualified class names of the discounts. In case of a 10 and 20 dollar gift card you would use the name "Gift card - 10 dollar" and "20 dollar" and both of them the discountable_type of "Namspace\For\AbsoluteDiscount\AbsoluteDiscount".

What i am thinking i am needing to do is:

But then we also have methods: get, first, all and maybe more that need to be overridden. And what about saving? And these steps need to be done for all 3 discount models. Is there an easy way to do it like this or is this something i must not do?

Upvotes: 4

Views: 4729

Answers (1)

igronus
igronus

Reputation: 486

I think you can use this trait here: https://github.com/Nanigans/single-table-inheritance

However, it based on singleTableTypeField attribute, which doesn't allow to get a child by conditions, only by some kind of type_id column. But I think it would be not so difficult to modify it to fit your needs.

Upvotes: 2

Related Questions