问题描述
我认为我不完全了解关联表.我知道如何使用普通表,即添加行,但不添加行,但是我不知道如何使用关联表.
I don't think I fully understand association tables. I know how to work with normal tables i.e add rows and what not but I don't understand how to work with an association table.
我为什么要使用以下内容
why would I use the below
student_identifier = db.Table('student_identifier',
db.Column('class_id', db.Integer, db.ForeignKey('classes.class_id')),
db.Column('user_id', db.Integer, db.ForeignKey('students.user_id'))
)
VS
class studentIdent(db.model):
db.Column(db.Integer, db.ForeignKey('classes.class_id')),
db.Column(db.Integer, db.ForeignKey('students.user_id'))
推荐答案
如对该问题的评论中所述,如果关联表仅包含外部表,则不必为该表创建 class
键以多对多关系链接两个表.在这种情况下,您的第一个示例-关联表 –就足够了.
As mentioned in a comment to the question, you would not bother creating a class
for the association table if it only contains the foreign keys linking the two tables in the many-to-many relationship. In that case your first example – an association table – would be sufficient.
但是,如果要存储有关两个表之间链接性质的其他信息,则需要创建 关联 object ,因此您可以操纵这些附加属性:
However, if you want to store additional information about the nature of the link between the two tables then you will want to create an association object so you can manipulate those additional attributes:
class StudentIdent(db.Model):
__tablename__ = "student_identifier"
course_id = db.Column(
db.Integer,
primary_key=True,
autoincrement=False,
db.ForeignKey('courses.course_id')
)
user_id = db.Column(
db.Integer,
primary_key=True,
autoincrement=False,
db.ForeignKey('students.user_id')
)
enrolment_type = db.Column(db.String(20))
# reason for student taking this course
# e.g., "core course", "elective", "audit"
然后您可以通过创建关联对象的新实例来创建给定学生与特定课程之间的链接:
and then you could create the link between a given student and a particular course by creating a new instance of the association object:
thing = StudentIdent(course_id=3, user_id=6, enrolment_type="elective")
注意:这只是一个基本链接.您可以通过明确声明关系来变得更加复杂.a>在ORM对象之间.
Note: This is just a basic linkage. You can get more sophisticated by explicitly declaring a relationship between the ORM objects.
这篇关于关联表和常规表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!