class PigeonView(db.Model):
__table_args__ = {'info': dict(is_view=True)}
id = db.Column(db.Integer, db.ForeignKey('pigeon.id')
kick_events = db.Column(db.Integer)
class PigeonBase(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=False)
date_created = db.Column(db.DateTime, nullable=False)
mySQL映射到一个表,PigeonView映射到一个视图( DB是Pigeon )。
这是视图:
CREATE VIEW pigeon_view AS
SELECT
p.id AS id,
COALESCE(SUM(k.pigeon_id), 0) AS kick_events
FROM pigeon p
LEFT JOIN kick_event k
ON p.Id = k.pigeon_id GROUP BY p.Id
基本上,只有一个鸽子ID和一个整数,表示鸽子被踢了多少次。
(还有另一个名为Kick Events的模型/表,该信息来自于该模型/表,如下所示)
class KickEvent(db.Model):
__tablename__ = "kick_event"
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
pigeon_id = db.Column(db.Integer, db.ForeignKey('pigeon.id'), primary_key=True)
date = db.Column(db.DateTime)
class Pigeon(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=False)
date_created = db.Column(db.DateTime, nullable=False)