首页 > 解决方案 > 多对多关系中的唯一约束

问题描述

我正在做一个 python 项目。在这个项目中,我使用的是 sqlalchemy。有两个表:notes 和 tags 以及创建多对多关系的第三个表 notes_tags。第三个表是这样定义的:

class NotesTags(Base):
    __tablename__ = 'notes_tags'
    id = Column(Integer, primary_key=True)
    note_id = Column('note_id', Integer, ForeignKey('notes.id'))
    note = relationship(Notes)
    tag_id = Column('tag_id', Integer, ForeignKey('tags.id'))
    tag = relationship(Tags)

当我将记录保存到此表时,我这样做:

notesTags.tag = newtag
notesTags.note = givenNote
session.add(notesTags)

在我的数据库中,我得到如下信息:

+----+---------+--------+
| id | note_id | tag_id |
+----+---------+--------+
|  1 |      83 |      1 |
|  2 |     108 |      1 |
|  3 |     114 |      1 |
|  4 |     119 |      1 |
|  5 |     124 |      1 |
+----+---------+--------+
5 rows in set (0.000 sec)

但是,如果我再次运行该过程,记录会重复,这意味着我会得到这样的东西:

+----+---------+--------+
| id | note_id | tag_id |
+----+---------+--------+
|  1 |      83 |      1 |
|  2 |     108 |      1 |
|  3 |     114 |      1 |
|  4 |     119 |      1 |
|  5 |     124 |      1 |
|  6 |      83 |      1 |
|  7 |     108 |      1 |
|  8 |     114 |      1 |
|  9 |     119 |      1 |
| 10 |     124 |      1 |
+----+---------+--------+
10 rows in set (0.000 sec)

这不是预期的结果。如何确保记录不重复?我想到了以下几点:a)在我保存记录之前检查是否已经存在具有给定 note_id - tag_id 的记录。b) 为使用 note_id 和 tag_id 的表创建复合 id

我不确定如何创建第二个以及什么是实现的最佳选择,或者我还能如何实现这一点。

如果这有什么不同,我将连接到 mysql 数据库。

任何帮助,将不胜感激。

标签: pythonmysqlsqlsqlalchemy

解决方案


推荐阅读