【问题标题】:How to create multiple relationships for multiple foreign keys pointing to the same table?如何为指向同一个表的多个外键创建多个关系?
【发布时间】:2015-05-09 06:27:18
【问题描述】:

让我们假设以下两个 MySQL 表:

-- -----------------------------------------------------
-- Table `mydb`.`Person`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`Person` (
  `id` INT NOT NULL ,
  `first_name` VARCHAR(45) NOT NULL ,
  `last_name` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `mydb`.`Parents`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `mydb`.`Parents` (
  `person_id` INT NOT NULL ,
  `mother` INT NOT NULL ,
  `father` INT NOT NULL ,
  PRIMARY KEY (`person_id`) ,
  INDEX `mother_idx` (`mother` ASC) ,
  INDEX `father_fk_idx` (`father` ASC) ,
  CONSTRAINT `person_fk`
    FOREIGN KEY (`person_id` )
    REFERENCES `mydb`.`Person` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `mother_fk`
    FOREIGN KEY (`mother` )
    REFERENCES `mydb`.`Person` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `father_fk`
    FOREIGN KEY (`father` )
    REFERENCES `mydb`.`Person` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

两个表之间有3个一对多的关系。

SQLAlchemy 使用的模型类可以类似于:

class Person(Base)
    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)

class Parents(Base)
    person_id = Column(Integer, ForeignKey('person.id'), primary_key=True)
    mother_id = Column(Integer, ForeignKey('person.id'))
    father_id = Column(Integer, ForeignKey('person.id'))

这是要添加到Parents 表中的三个backref 关系:

person = relationship(Person, backref=backref('parents', uselist=True))
mother = relationship(Person, backref=backref('mothers', uselist=True))
father = relationship(Person, backref=backref('fathers', uselist=True))

很遗憾,这些关系无效;创建表时没有错误,但尝试插入时出现以下错误:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship ...

作为 SQLAlchemy 的新手,我遇到了这种情况。请指教。

[编辑 1]

对代码的小修正。

【问题讨论】:

    标签: python sql sqlalchemy foreign-keys foreign-key-relationship


    【解决方案1】:

    我找到了解决方案here。关键是使用foreign_keys 参数。

    因此,关系可能类似于:

    person = relationship(Person, backref=backref('parents', uselist=True), foreign_keys=person_id)
    mother = relationship(Person, backref=backref('mothers', uselist=True), foreign_keys=mother_id)
    father = relationship(Person, backref=backref('fathers', uselist=True), foreign_keys=father_id)
    

    (我已将其添加为答案,因为它是问题的解决方案并且有效。我不知道这是否是在 SQLAlchemy 中做事的正确方法,因此,我期待任何其他答案/替代方案。)

    【讨论】:

      猜你喜欢
      • 2017-01-09
      • 1970-01-01
      • 2020-11-28
      • 2017-11-10
      • 2021-10-25
      • 2023-04-02
      相关资源
      最近更新 更多