如何在 sequelize 中创建关系对象?

How to create an object of a relationship in sequelize?

嘿,我需要在 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() 方法,在客户端 table 中添加了一个 SellerId。我想要做的只是能够在创建客户时将 id 传递给 ORM,以便它自动与卖家建立关系 table。

Sequelize Documentation about this

感谢您花时间阅读本文。我希望你能帮帮我!祝你有美好的一天。

首先,我更愿意在模型中定义一个外键列,并在关联中明确指出它。当然,您需要添加另一个从 clientssellers - 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
})