简体   繁体   中英

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. I have a Sale table to record the item sold/purchased by a user.

Im currently planning to give User a starting schema that looks like this:

id
user_name
display_name
... (other attrs)

A Sale would have a starting schema like this:

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. The end state is the same, but I'm not sure which way is better/recommended, and why.

Option 1 (using Sequelize.js format):

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

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

Option 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. 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.

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

Note that Sale table is usually used in OLAP, hence it is slightly denormalized. In OLTP you have usually document or event tables which contains seller and buyer IDs in the headers. Ie

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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