mysql - Sequelize 使用 postgres 方言添加双列

标签 mysql node.js postgresql express sequelize.js

我想在 parents 表和 children 表之间创建关系,这就是我的做法

// 20210226075430-create-child.js (children migration file)

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("Children", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      name: {
        type: Sequelize.STRING,
      },
      age: {
        type: Sequelize.STRING,
      },
      parentId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        onDelete: "CASCADE",
        references: {
          model: "Parents",
          key: "id",
        },
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("Children");
  },
};

// parent migration file

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("Parents", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      name: {
        type: Sequelize.STRING,
      },
      age: {
        type: Sequelize.STRING,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("Parents");
  },
};

// child.js / children model

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Child extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Child.belongsTo(models.Parent, { foreignKey: "parentId" });
    }
  }
  Child.init(
    {
      name: DataTypes.STRING,
      age: DataTypes.STRING,
      parentId: DataTypes.INTEGER,
    },
    {
      sequelize,
      modelName: "Child",
    }
  );
  return Child;
};

// parent model

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Parent extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Parent.hasMany(models.Child);
    }
  }
  Parent.init(
    {
      name: DataTypes.STRING,
      age: DataTypes.STRING,
    },
    {
      sequelize,
      modelName: "Parent",
    }
  );
  return Parent;
};

这段代码在 mysql 中完全没问题,但是当我将方言更改为 postgres 时,我得到了这样的错误:
Executing (default): SELECT "id", "name", "age", "parentId", "createdAt", "updatedAt", "ParentId" FROM "Children" AS "Child";
(node:7496) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "ParentId" does not exist
    at Query.formatError (D:\work\www\express-starter\node_modules\sequelize\lib\dialects\postgres\query.js:386:16)
    at Query.run (D:\work\www\express-starter\node_modules\sequelize\lib\dialects\postgres\query.js:87:18)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:7496) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7496) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我已经尝试在 child.js(模型)中添加外键,但我仍然遇到此错误。
我哪里做错了?

最佳答案

您没有在从 parentIdforeignKey 的关联中将 Parent 指示为 Children 选项,这就是 Sequelize 自动生成其名称(如 ParentId )的原因。
只需指示与 belongsTo 中相同的选项和值,如下所示:

Parent.hasMany(models.Child, { foreignKey: "parentId" });

关于mysql - Sequelize 使用 postgres 方言添加双列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66463150/

相关文章:

php - 通过将结果保存到文本文件来减少 MySQL 查询

php - 保存简单的复选框 bool 值 php

javascript - 如何以低延迟流式传输实时音频

postgresql - 测试 PostgreSQL 函数

json - 否定 ?& JSON 运算符

python - Pandas 应用处理比现有数据框更多的行

windows - 使用 node-webkit 应用程序设计系统托盘

javascript - 在 Node.Js 中的 express-validator 之前 trim 输入值

java - 如何从数据库存储和读取公钥?我正在使用 postgresql 和 java

php - PDO BindParam 和 BindValue 不起作用