简体   繁体   English

SQL多个多对多自引用关联(Sequelize.js)

[英]SQL Multiple Many-to-many Self-referencing Associations (Sequelize.js)

just wondering if the following thing is the proper thing to do. 只是想知道以下事情是否正确。

I have a User table, in which a user can be a buyer or a seller. 我有一个User表,其中用户可以是买家或卖家。 I have a Sale table to record the item sold/purchased by a user. 我有一个Sale表来记录用户出售/购买的物品。

Im currently planning to give User a starting schema that looks like this: 我目前正计划为User一个类似于以下内容的启动模式:

id
user_name
display_name
... (other attrs)

A Sale would have a starting schema like this: Sale将具有这样的起始模式:

id
product_id
price
... (other relevant attrs)

The part I'd like to ask about is the associations. 我想问的部分是关联。 There are two ways of doing it from what I see. 从我的角度来看,有两种方法可以做到这一点。 We could either establish 2 many-to-many rules for buyer and sellers respectively, or to have sale belong to User twice once as buyer and once as seller. 我们可以分别为买方和卖方建立2条多对多规则,或者让sale两次属于User一次,作为买方一次,一次作为卖方。 The end state is the same, but I'm not sure which way is better/recommended, and why. 最终状态是相同的,但是我不确定哪种方法更好/推荐什么,为什么。

Option 1 (using Sequelize.js format): 选项1(使用Sequelize.js格式):

User.belongsToMany(User, {
    through: Sale,
    as: 'buyer',
    foreignKey: 'buyer_id',
}

User.belongsToMany(User, {
    through: Sale,
    as: 'seller',
    foreignKey: 'seller_id',
}

Option 2: 选项2:

Sale.belongsTo(User, {
    foreignKey: 'seller_id',
}

Sale.belongsTo(User, {
    foreignKey: 'buyer_id',
}

In the end, both options result in the foreign key columns buyer_id and seller_id added to the Sale model. 最后,两个选项都将外键列buyer_idseller_id添加到Sale模型中。 But which approach would you recommend? 但是您会推荐哪种方法? And why? 又为什么呢?

Sale is the association table that implements among other things the many-to-many relation between sellers and buyers. Sale是关联表,它实现了买卖双方之间的多对多关系。

id
product_id
price
seller_id
buyer_id
... (other attrs)

Note that Sale table is usually used in OLAP, hence it is slightly denormalized. 请注意, Sale表通常在OLAP中使用,因此它被略微标准化了。 In OLTP you have usually document or event tables which contains seller and buyer IDs in the headers. 在OLTP中,通常具有文档或事件表,其表头中包含卖方和买方ID。 Ie

orders
----
id
date
seller_id
buyer_id
...

order_items
----
order_id
item_index
product_id
price
qty
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM