账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何在sqlalchemy建立外键foreignkey可以关联自己这张表,比如评论关联回复,评论和回复都属于Comment
    28
    0

    问题描述

    问题出现的环境背景及自己尝试过哪些方法

    相关代码

    // 请把代码文本粘贴到下方(请勿用图片代替代码)
    class Comment(Model):

    """

    评论和回复

    """
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True, autoincrement=True)
    comments = relationship('Comment', back_populates='comment')
    parent_comment_id = Column(Integer, ForeignKey('comment.id'), nullable=True)
    

    你期待的结果是什么?实际看到的错误信息又是什么?

    sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Comment.comments - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 在SQLAlchemy中,你可以使用relationship() 函数来创建外键。这是一个通用的方法,适用于所有类型的外键关系。

      首先,你需要在Comment表中创建一个外键,该外键关联Comment表的id字段。例如:

      ```python from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship

      class Comment(Base): tablename = 'comments'

      id = Column(Integer, primary_key=True)
      content = Column(String)
      author_id = Column(Integer, ForeignKey('users.id'))
      author = relationship('User', backref='comments')
      

      ```

      在这个例子中,Comment表有一个外键author_id,它关联Comment表的author_id字段。author_id字段是一个外键,它关联到users表的id字段。

      然后,你可以使用relationship() 函数来定义评论和回复之间的关系:

      ```python class Comment(Base): tablename = 'comments'

      id = Column(Integer, primary_key=True)
      content = Column(String)
      author_id = Column(Integer, ForeignKey('users.id'))
      author = relationship('User', backref='comments')
      

      ```

      在这个例子中,Comment表有一个外键author_id,它关联Comment表的author_id字段。author_id字段是一个外键,它关联到users表的id字段。同时,Comment表还有一个外键reply_id,它关联Comment表的reply_id字段。reply_id字段是一个外键,它关联到comments表的reply_id字段。这个关系表示一个评论可以有多个回复。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部