【问题标题】:How to create an object of a relationship in sequelize?如何在sequelize中创建关系对象?
【发布时间】:2021-03-22 06:16:25
【问题描述】:

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

Sequelize Documentation about this

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

【问题讨论】:

  • 您需要创建一个与现有卖家关联的新客户吗?
  • 感谢您的回复!。是的,这就是我想做的。

标签: node.js express sequelize.js


【解决方案1】:

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

【讨论】:

  • 感谢您的精彩回复!我有一个问题,为什么在建立卖方与客户的关系时使用foreignKey:'sellerId'?它不会在 Sellers 表中创建一个名为“sellerId”的字段吗?
  • 没有。 hasMany 中的 foreignKey 选项表示传递模型中的字段作为第一个参数(在这种情况下为 Clients
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-07
相关资源
最近更新 更多