简体   繁体   中英

Laravel Eloquent - Multiple models for one table

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

  • AbsoluteDiscount
  • OneProductForFreeDiscount
  • QuantityDiscount

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:

  • id
  • name
  • discountable_type
  • active
  • valid_from
  • valid_until

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:

  • Create a base eloquent model for those discount models to extend.
  • Override the where method in each discount, appending an additional where method call to it with this as its content ('discountable_type', '=', AbsoluteDiscount::class) before returning it.

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?

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.

Well, this isn't a Polymorphic relation but looks a bit like it. A polymorphic relation specifies that a model belongs to one or more other models. This is different situation since these models don't belong to other models but are all alike. I don't know what a solution for this could be

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM