我是 sqlalchemy 的新手。现在用 Flask 开发网站。我想用线程组织消息系统。类似于 facebook 对话框之类的东西。我有以下模型,并且此代码有效:
message_read_state_relations = db.Table('message_message_read_state_relations',
db.Column('user_id', db.Integer, db.ForeignKey('auth_users.id')),
db.Column('message_id', db.Integer, db.ForeignKey('messages.id')),
)
class User(db.Model):
__tablename__ = 'auth_users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100))
password = db.Column(db.String(100))
messages = db.relationship('Message', backref=db.backref('user'), lazy='dynamic')
threads = association_proxy('user_thread_relations', 'thread')
class Message(db.Model):
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.Text, default='')
thread_id = db.Column(db.Integer, db.ForeignKey('threads.id'))
user_id = db.Column(db.Integer, db.ForeignKey('auth_users.id'))
user_read_states = db.relationship('User', secondary=message_read_state_relations,
backref=db.backref('message_read_states'), lazy='joined')
class Thread(db.Model):
__tablename__ = 'threads'
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.String(255))
messages = db.relationship('Message', backref=db.backref('thread'), lazy='dynamic')
users = association_proxy('user_thread_relations', 'user')
class UserThreadRelation(db.Model):
__tablename__ = 'user_thread_relations'
user_id = db.Column(db.Integer, db.ForeignKey('auth_users.id'), primary_key=True)
thread_id = db.Column(db.Integer, db.ForeignKey('threads.id'), primary_key=True)
is_deleted = db.Column(db.Boolean, default=False)
user = db.relationship(User, backref=db.backref('user_thread_relations'))
thread = db.relationship(Thread, backref=db.backref('user_thread_relations'))
但是有些东西我看不懂。例如,如何获取用户的所有未读消息计数?或者在某些线程中未读消息对用户计数?
Message
User
与via有关系message_read_state_relations
。如何获取属于该用户而不属于message_read_state_relations
该用户的所有线程的所有消息?
或者,也许,我做错了?设计错了吗?我基于这个问题线程消息系统数据库架构设计创建它
谢谢你的帮助!