如何为指向同一表的多个外键创建多个关系?

2024-06-10 08:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有以下两个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使用的模型类可以类似于:

^{pr2}$

下面是要添加到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]

对代码做了一些小的修改。


Tags: keynoidonnotactionnullint
1条回答
网友
1楼 · 发布于 2024-06-10 08:21:01

我找到了一个解决方案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中正确的方法,因此,我期待其他答案/替代方法。)

相关问题 更多 >