2

Suppose i have 2 tables , Table 1 consist of users info and Table 2 consist of Branch info. table 1 and table 2 is related to each other by many to many relationship. e.g 1 user can work in multiple branches and 1 branch can have multiple users. so here there's no parent child concept. i was wondering if i have to create another table with schema and relate it to user and branch table using foreign key or shall i create an association table.

I have done this :

class UserBranchMap(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    branch_id = db.Column(db.Integer,db.ForeignKey('branch.id'))
    branch = db.relationship("Branch", backref=db.backref("UBMbranch", lazy="dynamic"))
    user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    user = db.relationship("User", backref=db.backref("UBMuser", lazy="dynamic"))
    created_at = db.Column(db.VARCHAR(20), nullable = False)
    created_by = db.Column(db.VARCHAR(20), nullable = False)

class UserBranchMapSchema(ma.Schema):
    branch = fields.Nested(branch_schema)
    user = fields.Nested(user_schema)
    class Meta:
        fields = ('branch_id','user_id','created_at','created_by')

userbranchmap_schema = UserBranchMapSchema()
userbranchmaps_schema = UserBranchMapSchema(many = True)

what's the difference between association table and this mapping table ?

4

1 回答 1

3

如果我理解正确,您是在询问关联表之间的区别

UserBranches = db.Table(
    'user_branches',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    db.Column('branch_id', db.Integer, db.ForeignKey('branch.id'), primary_key=True)
)

和一个映射表

class UserBranch(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user = db.relationship("User", backref=db.backref("UBMuser", lazy="dynamic"))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    branch = db.relationship("Branch", backref=db.backref("UBMbranch", lazy="dynamic"))
    branch_id = db.Column(db.Integer, db.ForeignKey('branch.id'))

在数据库级别上,它们之间没有真正的区别。如果您只想在两个表之间建立严格的多对多关系,只需使用关联表即可。由于 SQLAlchemy,您永远不必对它做任何事情,因为只要您将用户连接到分支或相反,通过此表连接就会自动发生。

但是,如果您想做更多事情,比如让它实际上表示一个关系,那么像您编写的映射表是可行的,因为它的行为与普通表完全一样。这意味着您可以像使用它一样使用它UserBranch.created_at,甚至可以根据需要直接查询它。

于 2020-08-01T12:47:53.540 回答