问题原型是,现在要实现用户之间的互相能够关注的功能,反应到数据库中是一个多对多的关系,书里引入了第三个关联表,模型是这么定义的(用户表是users,主键定义为id):
class Follow(db.Model):
__tablename__ = 'follows'
follower_id = db.Column(db.Integer, db.ForeignKey('users.id'),
primary_key=True)
followed_id = db.Column(db.Integer, db.ForeignKey('users.id'),
primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
Follow表中的每条记录代表着一个user关注另一个user,那么不论是follower_id列还是followed_id列都必然会出现重复。那么:
1.在这种情况下为何还能定义成主键呢?
2.如果不定义成主键会有什么不同?(是不能用了还是性能下降还是什么别的?)
I saw it in the SQLAlchemy documentation, so the usage here should be a composite primary key.
A table has only one primary key, and multiple primary keys cannot be set at the same time.
follower_id and followed_id should be set as unique keys, that is, unique key.