繁体   English   中英

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

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

只是想知道以下事情是否正确。

我有一个User表,其中用户可以是买家或卖家。 我有一个Sale表来记录用户出售/购买的物品。

我目前正计划为User一个类似于以下内容的启动模式:

id
user_name
display_name
... (other attrs)

Sale将具有这样的起始模式:

id
product_id
price
... (other relevant attrs)

我想问的部分是关联。 从我的角度来看,有两种方法可以做到这一点。 我们可以分别为买方和卖方建立2条多对多规则,或者让sale两次属于User一次,作为买方一次,一次作为卖方。 最终状态是相同的,但是我不确定哪种方法更好/推荐什么,为什么。

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

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

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

选项2:

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

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

最后,两个选项都将外键列buyer_idseller_id添加到Sale模型中。 但是您会推荐哪种方法? 又为什么呢?

Sale是关联表,它实现了买卖双方之间的多对多关系。

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

请注意, Sale表通常在OLAP中使用,因此它被略微标准化了。 在OLTP中,通常具有文档或事件表,其表头中包含卖方和买方ID。

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