嘿,我需要在 Sequelize 中建立关系。我有模型并且在数据库中很好地创建。
我会向你展示我的模型,但它不是很相关。
卖家模型
const Sellers = db.define("sellers", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: Sequelize.STRING,
surname: Sequelize.STRING,
});
Sellers.hasMany(Clients);
module.exports = Sellers;
客户端模型 const Client = db.define("clients", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: Sequelize.STRING,
creationDate: Sequelize.DATE,
client_type: Sequelize.STRING,
});
module.exports = Client;
我想做的 只是在客户和卖家之间建立关系。在数据库中,由于 sequelize hasMany()
方法,在客户端表中添加了 SellerId。我想要做的只是能够在创建客户端时将 id 传递给 ORM,以便它自动将关系建立到卖家表。Sequelize Documentation about this
感谢您花时间阅读本文。我希望你能帮帮我!祝你有美好的一天。
最佳答案
首先,我更喜欢在模型中定义一个外键列并在关联中明确指出它。当然,您需要添加从 clients
到 sellers
的另一个关联 - belongsTo
并在模型外部调用这两个关联,以便能够相互引用它们。
客户端模型文件:
const Client = db.define("clients", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: Sequelize.STRING,
creationDate: Sequelize.DATE,
client_type: Sequelize.STRING,
sellerId: {
type: Sequelize.INTEGER,
allowNull: false // or true if this association is optional
},
});
一些 database.js
文件,您应该在其中注册所有关联:....
Sellers.hasMany(Clients, { foreignKey: 'sellerId' });
Clients.belongsTo(Sellers, { foreignKey: 'sellerId' });
然后您可以创建一个指示卖家 ID 的客户端:const seller = await Seller.findOne({
where: {
name: 'Peter'
}
})
const newClient = await Client.create({
name: 'John',
sellerId: seller.id,
// other fields here
})
关于node.js - 如何在 sequelize 中创建关系的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66737597/