0

enter image description here

How can I ensure that the shop_has_product table is from the same company? Is there a way to achieve this is RDBMS or do I need write the insert logic in the application layer.

Thanks you for your time.

1 Answers1

1

In MySQL, you can make a foreign key reference any KEY of the referenced table, not just the primary key. So create a KEY over the id with the company_id in each table.

CREATE TABLE company (
 id INT PRIMARY KEY,
 name VARCHAR(45)
);

CREATE TABLE product (
 id INT PRIMARY KEY,
 company_id INT NOT NULL,
 KEY (id, company_id),
 FOREIGN KEY (company_id) REFERENCES company(id)
);
    
CREATE TABLE shop (
 id INT PRIMARY KEY,
 name VARCHAR(45),
 company_id INT NOT NULL,
 KEY (id, company_id),
 FOREIGN KEY (company_id) REFERENCES company(id)
);

Then add a company_id column to the many-to-many table, and use the same colum in two foreign keys, one to each of the above tables. Naturally, company_id must have the same value in both foreign keys on a given row.

 CREATE TABLE shop_has_product (
 shop_id INT NOT NULL,
 product_id INT NOT NULL,
 company_id INT NOT NULL,
 PRIMARY KEY (shop_id, product_id),
 FOREIGN KEY (shop_id, company_id) REFERENCES shop(id, company_id),
 FOREIGN KEY (product_id, company_id) REFERENCES product(id, company_id)
);
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828