I have a MySQL table in order to manage building entrance methods in a city described by the following model:
class EntranceMethod(db.Model):
id = Column(String, primary_key=True)
building_id = ForeignKey('building.id', nullable=False)
user_id = ForeignKey('user.id', nullable=False)
card_name = Column(String, nullable=False)
gate = Column(Enum('A', 'B', 'C'), nullable=False)
In a building, a person can have many cards, which can be used to identify them and allow them to go through certain gates. However, these cards also can be used to do that at other buildings.
In a building scope, I want to ensure that:
- With a specific gate, an user cannot use more than 1 card to enter. (They can enter the building at other gates by this card but cannot use another card at this gate).
So I created an unique constraint: (building_id
, user_id
, gate
)
- A card belongs to only 1 user.
What constraint should I make? I thought of a unique constraint for building_id
, card_name
, gate
will solve the problem, but its just say that, 'This card can be used by only one user on each gate'. The case, user U use card K at gate A, and user V use card K at gate B, is still able to be.
For example, I have some records (one building scope):
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…