0

我正在制作一个社交媒体网络应用程序,我创建了一个名为 User 的模型,它有两个关系帖子(这工作正常)和朋友(自我引用)。我已经迁移了数据库,它运行良好。我还通过数据库浏览工具添加了关注者,效果很好。

friendship = db.Table(
    "friendships",
    db.Model.metadata,
    db.Column("user_id", db.Integer, db.ForeignKey("user.id"), index=True),
    db.Column("friend_id", db.Integer, db.ForeignKey("user.id")),
)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    friends = db.relationship(
        "User",
        secondary=friendship,
        primaryjoin=id == friendship.c.user_id,
        secondaryjoin=id == friendship.c.friend_id,
    )

    def follow(self, friend):
        if friend not in self.friends:
            self.friends.append(friend)

    def unfollow(self, friend):
        if friend in self.friends:
            self.friends.remove(friend)

我写了一个简单的查询来查找用户正在关注的人。这工作正常。 following = current_user.friends

我正在尝试编写一个查询来列出关注用户的人(类似于常见的社交媒体应用程序,如 Instagram),但我正在努力处理这个查询。这是我尝试过的,但它不起作用。

followers = db.session.query(friendship).filter_by(friend_id=current_user.id)

我遇到的另一个问题是编写查询以查找用户当前未关注的人。

I'm not very experienced with databases, which is why I am struggling with these queries. Thanks in advance for any help. I have also tried looking at similar posts but none of them are quite what I am looking for.

4

1 回答 1

0

You will need to write a query to join the table to an aliased version of itself. SQLAlchemy Docs

from sqlalchemy.orm import aliased

user_id = ... # id of the user whose followers you want to find

UserAlias = aliased(User)
followers = User.query.join(UserAlias.friends).with_entities(UserAlias).all()
于 2021-01-08T14:51:42.610 回答