node.js - 如何在 sequelize 中创建关系的对象?

标签 node.js express sequelize.js

嘿,我需要在 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
感谢您花时间阅读本文。我希望你能帮帮我!祝你有美好的一天。

最佳答案

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

关于node.js - 如何在 sequelize 中创建关系的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66737597/

相关文章:

javascript - 如何使用 koa-bodyparser 在 koa 中获取查询字符串?

mongodb - 如何检查数据库(mongodb)中是否存在用户名和密码

node.js - NPM 5 的依赖项和 devDependency 之间有什么区别

javascript - 检查项目 Package::JSHINT 中的所有 JS 文件

node.js - 使用 Sequelize/Node.js,如何将笨拙的 TEXT 数据类型插入到 postgres 数据库中?

node.js - Jade 模板传承

javascript - sequelize scope with concatted where

node.js - 如何在 Node.js 中的 Sequelize Mock 中为 Sequelize.js 原始查询编写测试用例

javascript - 表之间的序列化和查询

node.js - 类型 'catch' 上不存在属性 'Promise<void>'