4

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?

1
  • 1
    Have you had a look at Polymorphic Relations in the docs? laravel.com/docs/5.6/… Commented Mar 1, 2018 at 20:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.