如何在SQLAlchemy中的两个表之间建立两个相似的关系?

时间:2020-09-29 17:28:31

标签: sqlalchemy flask-sqlalchemy

我已经多次回到并放弃了。

从技术上讲,如果有所不同,那就是flask-sqlalchemy。我想我要做的是在Pair表中建立两个多对一(或者是一对一?)关系,它们都引用Word表。一对必须有两个单词,一个单词可以成对出现。

class Pair(db.Model):
    __tablename__ = "pairs"

    id = db.Column(db.Integer, primary_key=True)

    word_id = db.Column(db.Integer, db.ForeignKey('words.id'), nullable=False)
    partner_id = db.Column(
        db.Integer, db.ForeignKey('words.id'), nullable=False)

    word_sound = db.Column(db.String(), nullable=False)
    partner_sound = db.Column(db.String(), nullable=False)

    # These two relationships are where I'm particularly lost. The words 1 and 2 need to
    # refer to two separate sounds, so I can't just have two words and two sounds in any
    # order. Therefore I need to have two one-to-one links to the same table:

    word1t = db.relationship(
        "Word", foreign_keys=[word_id], primaryjoin="Pair.word_id==Word.id",, back_populates="pairs")
    word2t = db.relationship(
        "Word", foreign_keys=[partner_id], primaryjoin="Pair.partner_id==Word.id", back_populates="pairs")





class Word(db.Model):

    __tablename__ = "words"

    id = db.Column(db.Integer, primary_key=True)
    word = db.Column(db.String(), nullable=False)

    # Relationships

    # "partners" refers to all words that this word has a pair (link) with
    partners = db.relationship(
        'Word',
        secondary="pairs",
        primaryjoin=id == Pair.word_id,
        secondaryjoin=id == Pair.partner_id,
        backref=db.backref('words')
    )
    # "pairs" is supposed to refer to all pairs that this word is a part of.
    pairs = db.relationship('Pair', primaryjoin=id ==
                        or_(Pair.word_id, Pair.partner_id))

我有这些模型。基本上,我有单词和(单词对),其中,单词对由两个单词组成,并且还包含一些关于单词对类型的信息。在一对中,我需要两个不同的词,每个词都有自己的声音。该声音由单词与另一个单词的对应关系定义,因此fx在“ pat”和“ hat”对中,“ pat”具有“ p”,“ hat”具有“ h”,因为这些声音包含了话。所以什么声音与什么单词相关才是重要的。但是我不能只将声音放在Word表中,因为例如,当链接到“ pac”时,“ pat”具有不同的声音(t)。

我尝试了很多事情,然后又删除了它们,但现在我只是希望有人能向我展示正确的方法。

帮我,Stackoverflow。你是我唯一的希望。

0 个答案:

没有答案
相关问题