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 manylocations
and arestaurant
can have manyoffers
.
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 certainlocations
of arestaurant
.
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?
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