javascript - 如何在 Sequelize JS 和 PostgreSQL 中的 1 :M relationship when implementing with . bulkCreate() 中使用外键

标签 javascript node.js postgresql foreign-keys sequelize.js

我正在编写一个可以从 (.csv) 数据集中提取数据的脚本。我能够将数据拉入控制台,创建新表并将数据插入数据库。

我想弄清楚如何在实现 .bulkCreate() 时设置外键。当我坚持使用常规 .create() 时,出现资源错误。

数据集保存在 2 个数组中:

  • 竞争对手Objs
  • meetObjs

  • 到目前为止,这是我尝试插入数据的方式:
    sequelize.sync().then(() => {
    
    meets.bulkCreate(meetObjs).then(data => {
    
        competitorObjs.forEach(x => {
    
            competitors.create({
                MeetID: x.MeetID,
                Name: x.Name,
                Sex: x.Sex,
                Equipment: x.Equipment,
                Age: x.Age,
                Division: x.Division,
                BodyweightKg: x.BodyweightKg,
                WeightClassKg: x.WeightClassKg,
                BestSquatKg: x.BestSquatKg,
                BestBenchKg: x.BestBenchKg,
                BestDeadlift: x.BestDeadlift,
                TotalKg: x.TotalKg,
                Place: x.Place,
                Wilks: x.Wilks,
                UserId: data.get("MeetID")   // Set FK here (Not sure if correct implementation)
            })
        })
    }).then(() => {
        console.log("Bulk Creation Success!");
    }).catch((err) => {
        console.log(err)});
    })
    

    脚本完成后,仅填充了“Meets”表,但“Competitors”保持空白。

    如何在每个“竞争对手”插入中设置外键以指向“Meets”表中的每个主键? (FK 未设置为唯一)

    最佳答案

    你快到了。您可以使用 index 循环

    competitorObjs.forEach((x, index) => {
      competitors.create({
    ...
    ..
    ..
      UserId: data[index]["MeetID"]
    

    这种方法的问题在于,要创建 N 个对象,您将创建 N + 1 个查询。 1 用于批量创建,N 用于关联表。您也可以在关联数组中使用 bulkCreate

    您可以遍历 competitorObjs ,如上所述填写 UserId ,然后执行 bulkCreate。

    关于javascript - 如何在 Sequelize JS 和 PostgreSQL 中的 1 :M relationship when implementing with . bulkCreate() 中使用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51072813/

    相关文章:

    javascript - 这是什么JS设计模式?

    javascript - 使用 Angular Material 上传文件

    javascript - InDesign 脚本 - 表格页脚和插入点

    json - sendFile 表达返回特殊字符

    mysql - 从 PostgreSQL 函数到 MySQL 的带有特殊字符的转换器名称 URI

    javascript - 在 React 中创建表单的最佳方式是什么?

    node.js - Knex Query 构建 - 动态构建链

    python - 在 GAE 上的 NodeJS 中使用 Python 脚本

    postgresql - pq 驱动程序 : prepared statement does not exist

    PostgreSQL 服务器未启动