mysql 无法确定多对多关联表的连接条件

fnatzsnv  于 2023-08-02  发布在  Mysql
关注(0)|答案(1)|浏览(113)

我正在尝试使用models.py和sqlalchemy创建一个多对多关联表。

from sqlalchemy import Column, Integer, String, Numeric, Boolean, DateTime, Table, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base 
Base = declarative_base()
cs_skin_case = Table('cs_skin_case', Base.metadata,
                    Column('cs_case_id', Integer, ForeignKey('cs_cases.id')),
                    Column('cs_skin_id', Integer, ForeignKey('cs_skins.id')))
class CS_SKINS(Base):
    __tablename__ = 'CS_SKINS'
    id = Column(Integer, primary_key=True)
    cs_cases = relationship("CS_CASES", secondary = cs_skin_case, back_populates= "cs_skins")
    
class CS_CASES(Base):
    __tablename__ = 'CS_CASES'
    id = Column(Integer, primary_key=True)
    skins = relationship("CS_SKINS", secondary = cs_skin_case, back_populates= "cs_cases")

字符串
它抛出了这个错误

sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship CS_SKINS.cs_cases - there are no foreign keys linking these tables via secondary table 'cs_skin_case'.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify 'primaryjoin' and 'secondaryjoin' expressions.```

when I try to append
```py
skin.cs_cases.append(case)
session.commit()


我期待的是:

  • 一个名为cs_skin_case的关联表,因此我可以使用sqlalchemistry连接cs_skins和cs_cases
  • skin.cs_cases.append(case)在skins_cases MySQL数据库中创建一行,其中包含case_id和skin_id

我尝试的是:

  • cs_skin_case创建单独的类
  • relationship()参数混乱
  • 理解Flask版本的SQLAlchemy,但没有成功
bis0qfac

bis0qfac1#

您的表名是CS_SKINSCS_CASES,因此您必须在ForeignKey('CS_SKINS.id')ForeignKey('CS_CASES.id')中使用相同的名称。
relationship("CS_CASES", secondary = cs_skin_case, back_populates= "cs_skins")中还有一个错误
必须是relationship("CS_CASES", secondary = cs_skin_case, back_populates= "skins")

相关问题