This is a simplified example of my current models (I'm using the Flask SQLAlchemy extension):
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'
)
I'm trying to order Post
's by the amount of likes it has.
This is the query I'm basically trying to issue:
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
I just haven't been able to get anything working on the SQLAlchemy side of things.
Thanks for any help anyone can offer.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…