这是我当前模型的简化示例(我正在使用Flask SQLAlchemy 扩展):
like = db.Table(
'like',
db.Column('uid', db.Integer, db.ForeignKey('users.id')),
db.Column('pid', db.Integer, db.ForeignKey('posts.id'))
)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(20))
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(255))
likes = db.relationship(
'User',
secondary = like,
backref = db.backref('likes', lazy = 'dynamic'),
lazy = 'dynamic'
)
我正在尝试按喜欢Post
的数量来订购 's 。
这是我基本上试图发出的查询:
SELECT p.*, COUNT(l.`pid`) as `likes`
FROM `posts` as p
LEFT JOIN `like` as l
ON p.`id` = l.`pid`
GROUP BY p.`id`
ORDER BY `likes` DESC
我只是无法在 SQLAlchemy 方面进行任何工作。
感谢任何人都可以提供的任何帮助。