mysql - Sequelize 插入级联

标签 mysql node.js sequelize.js

我正在尝试插入多个表。
让我解释一下用户创建一个新客户端,客户端将 id 插入到 bill - (idClient) 表中
这是有效载荷

{
  "name": "Evelyn",
  "lastName": "Doe",
  "phone": "4534534",
  "email": "eve@hotmail.com",
  "identification": "xxxxx",
  "services": [1, 2, 3],
  "bill":{
    "description": "New project"
  }
}
插入
_service.create = async (client) => {
 const { description } = client.bill;
 try {
   const data = await Client.create(
    { client, bill: { description: description } },
    { include: { model: Bill } }
   );
  return data.id;
} catch (err) {
    handleError = err.hasOwnProperty("errors")
      ? err.errors.map((error) => error.message)
      : err;
    throw new Error(handleError);
  }
};
但我收到这个错误
{
 "name": "Error",
 "message": "ReferenceError: description is not defined"
}
是的,帐单表有该列。
关系
Client.hasOne(models.Bill, { foreignKey: "idClient" });
所以,我被卡住了,我阅读了文档,我试图以与他们相同的方式做,但我不知道我做错了什么
https://sequelize.org/master/manual/creating-with-associations.html

最佳答案

我已经这样做了,我不知道是否是最好的方法
我修改了有效载荷

{
  "name": "Evelyn",
  "lastName": "Doe",
  "phone": "4534534",
  "email": "eve@hotmail.com",
  "identification": "xxxxx",
  "description": "new Proyect",
}
插入查询,将 bill 更改为 Bill 作为我的表名,然后添加描述值
const { description } = client;
const data = await Client.create(
  { ...client, Bill: { description } },
  { include: { model: Bill } }
);
结果
{
"id": 6,
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve@hotmail.com",
"identification": "xxxxx",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z",
"Bill": {
  "id": 4,
  "idClient": 6,
  "totalAmount": null,
  "description": "new Proyect",
  "idStatus": 2,
  "createdAt": "2020-11-13T08:52:37.000Z",
  "updatedAt": "2020-11-13T08:52:37.000Z"
  }
}

关于mysql - Sequelize 插入级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64817128/

相关文章:

angularjs - mean.io 使用 http 请求堆栈 Angular 长时间运行的操作

mysql - 从sequelize关联检索值时出错

sequelize.js - 带有Sequelize的递归父子查询?

mysql - 无法用 SQL 查询替换未知长度的字符串?

mysql - Rails 应用程序在请求 mysql 数据库时崩溃

node.js - IDE cloud9 中的 HTTP 身份验证

node.js - 如何使用 Node 传递JSON正文来调用REST服务?

sql - node.js Sequelize 交易

mysql查询具有多个评论的帖子

具有相同命名模式的 MySQL 更新