Enforcing common foreign key in many-to-many relationship

南笙酒味 提交于 2019-12-08 08:55:59

问题


I have the following interesting data modeling problem. I am going to use the example of restaurants to illustrate it: Consider the following three entities: Restaurant, Location and Offer.

  • A restaurant can have many locations and a restaurant can have many offers.

Those relationships are easy to represent: A Restaurant table; a Location table with a FK from the Restaurant table; and a Offer table with a FK from the Restaurant table.

The interesting problem comes now:

  • An offer can only be valid on certain locations of a restaurant.

The modeling of that restriction seems easy at the beginning: just do an association table with two foreign keys, one from the Offer table, and another one from the Location table.

The problem with that solution is that it does not restrict me from associating offers and locations that do not belong to the same restaurant.

How could I model this in a better way that would allow me to enforce that restriction at the database level?


回答1:


My assumption is that in your current model Location has 1 restaurant and Offer has 1 Restaurant.

You can solve your problem by making a compound key on Offer: (Restaurant_ID, Offer_ID) and use this key as a foreign key from Location_Offers to Offer.

You can do the same on Location: make a compound key (Restaurant_ID, Location_ID) and use this as a foreign key from Locations_Offer to Location.

This ensures that any record in Locations_Offer that links a Location and an Offer, only links those that have a relation with the same Restaurant.



来源:https://stackoverflow.com/questions/29659540/enforcing-common-foreign-key-in-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!