2

下面你可以看到我的数据库的一些表是如何相关的。

图表

如您所见,中间的表连接了 3 个具有多对多关系的表......

  1. 一种基因可以在多个器官中表达并在多个实验中进行研究
  2. 在一个器官中,可以表达多个基因,并且可以在多个实验中研究一个器官。
  3. 在一项实验中,可以研究多个基因和器官

我正在使用 SQLAlchemy 插入数据。我知道如何与连接 2 个表的表添加多对多关系,并且或多或少我是这样做的:

def add_data():
    session=Session()
    gene = "BRCA2"
    gene_to_add = Gene(gene_name = gene)
    session.add(gene_to_add)

    experiment = "experiment1"
    experiment_to_add = Experiment(experimentAccession = experiment)
    gene_to_add.experiment_rel.append(experiment_to_add)

    organ = "brain"
    organ_to_add = Organ(organName = organ)

    session.commit()
    session.close()

但我不知道如何添加新的关系(在这种情况下是器官表)。我尝试使用扩展而不是附加,但它不起作用......

有谁知道如何解决这种情况?也许数据库的结构应该改变......任何帮助将不胜感激

4

1 回答 1

2

您始终可以使用关联对象

class Genes2Experiments2Organs(Base):
    __tablename__ = 'genes2experiments2organs'
    gene_id = Column(Integer, ForeignKey('genes.id'), primary_key=True)
    experiment_id = Column(Integer, ForeignKey('experiments.id'), primary_key=True)
    organ_id = Column(Integer, ForeignKey('organs.id'), primary_key=True)
    # relationships
    gene = relationship("Gene", backref="map") 
    experiment = relationship("Experiment", backref="map") 
    organ = relationship("Organ", backref="map") 


class Gene(Base):
    __tablename__ = 'genes'
    id = Column(Integer, primary_key=True)
    gene_name = Column(String)

class Experiment(Base):
    __tablename__ = 'experiments'
    id = Column(Integer, primary_key=True)
    experimentAccession = Column(String)

class Organ(Base):
    __tablename__ = 'organs'
    id = Column(Integer, primary_key=True)
    organName = Column(String)

###########################################
def add_data():
    session = Session()
    gene = "BRCA2"
    gene_to_add = Gene(gene_name = gene)
    #session.add(gene_to_add)

    experiment = "experiment1"
    experiment_to_add = Experiment(experimentAccession = experiment)
    #session.add(experiment_to_add)

    organ = "brain"
    organ_to_add = Organ(organName = organ)
    #session.add(organ_to_add)

    #gene_to_add.experiment_rel.append(experiment_to_add)
    assoc_obj_to_add = Genes2Experiments2Organs(
        gene = gene_to_add,
        experiment = experiment_to_add,
        organ = organ_to_add,
        )

    session.add(assoc_obj_to_add)

    session.commit()
    session.close()

add_data()
于 2013-04-21T10:58:05.473 回答