Laravel (and not only) Many-to-many relationship Belongs-To-All

216 Views Asked by At

I have two tables. 'Products' and 'Discounts'. Then I create a joining table 'discount_product' for Many-to-many relationship. So far so good.

Now if I want a discount to belong to ALL of the products I have to make insertions into the joining table for as many products I have. That means that having 10000+ products I'll have to insert 10000+ rows for one discount into the joining table? And that's only for one discount! What if I have 1000?

That's compelling me into returning to the old (wrong) way of doing it when I just have a column 'product_ids' in the 'Discounts' table with something like this '1|2|4|7|23|...' (or '*' for 'belongs to all') and then make a small piece of PHP code to check if discount belongs to all or to some products. I know it's wrong way of doing it. So is there a better way to make this properly?

Structure:

**products**
  id 
  description
  price

**discounts**
  id
  procent
  value

**discount_product**
  product_id
  discount_id
1

There are 1 best solutions below

1
Zualex On

I propose to try to change some business logic.

  • If the discount is not in the discount_product then this means that it applies to all products.
  • If the discount is in the discount_product then it means that it works only for a certain product.
  • If you need to ensure that the discount is not applied to any product, add the field is_active in discounts.

It's just my thoughts.

I believe that sometimes it is useful to denormalize the database because of optimization, and I would do as you suggested with the product_ids field.