Discount calculation [closed]
Question
I'm currently designing a database for my company's website. I would like to create a table which will hold information (logic) about our discounts so that I can just call a function with a discountID and my php code will calculate the new price. My question is, every discount has different logic. ex. 10% off, $10 off, by one get one free, buy 3 get 50% off...
How can I store this in the database so that my code can calculate the discount on its own?
Solution
A database does not store logic - only data. Split this into three fields:
- discount amount (int)
- discount type (enum; possible values: 'percent', 'amount')
- buy one get N free (int; the number you get free for every one bought)
So for one discount you might store the following:
| discount amount | discount type | buy one get one free | ---------------------------------------------------------- | 10 | 'percent' | |
For another, where BOGOF applies:
| discount amount | discount type | buy one get N free | ---------------------------------------------------------- | | | 1 |
Then it would be up to your PHP to receive these values and act accordingly.
OTHER TIPS
You must to create discount table with such fields for example:
- discount_id - ID of the discount
- percent - % of discount (if 0 - then it's discount of other type)
- amount - amount of discount in $ (if 0 - then it's discount of other type)
- items - number of free items when buy something (one get - one free in your example)
- bought_items - condition, in what case you give a discount (if 0 - no conditions)
Or you can give other names to the fields. According to values you may know what type of discount and what condition to give it.
This is where I would normally start with a multi-tiered approach, since it not only will be for calculating but may be used to show on the actual website. I would start with two tables.
Promotion Table
| id | discount_type | qty_products | discount_amount | free_products |
-----------------------------------------------------------------------
| 1 | BOGO | 2 | 0 | 1 |
Sales Promo
| id | promo_id | product_id | activation_date | expiration_date |
------------------------------------------------------------------
| 1 | 1 | 222 | '2012-04-23' | '2012-05-12' |
Then the code would look to see if it was in date range and apply the discount or B1G1/B1G2. Tables are not exact but a start.