使用 sequelize 在 2 个现有表之间创建关联

Create association between 2 existing tables using sequelize

我有 2 个现有的(User 和 PaymentPlan)table创建时它们之间没有关联。

PaymentPlan.ts

import { DataTypes, Model } from "sequelize";
import { sequelize } from "./DBConnections/SequelizeNewConnection";

export class PaymentPlan extends Model{
  public ID: number;
  public months: number;
  public fees: number;
  public name: string;
  
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

PaymentPlan.init(
  {
    ID: {
      type: DataTypes.NUMBER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true,
    },
    months: { type: DataTypes.NUMBER },
    name: { type: DataTypes.STRING },
  },
  {
    tableName: "paymentplans",
    sequelize,
  },
);

User.ts

import { PaymentPlan } from "./PaymentPlan";
import { Model, DataTypes } from "sequelize";
import { sequelize } from "./DBConnections/SequelizeNewConnection";
    export class User extends Model{
      public ID: number;
      public name: string;
      public amount: number;
      public fees: number;
      public paymentPlan: number;
        
      public readonly createdAt!: Date;
      public readonly updatedAt!: Date;
    
    }
        User.init(
          {
            ID: {
              type: DataTypes.NUMBER,
              primaryKey: true,
              allowNull: false,
              autoIncrement: true,
            },
            name: { type: DataTypes.STRING },
            amount: { type: DataTypes.NUMBER },
            fees: { type: DataTypes.NUMBER },
            paymentPlan: { type: DataTypes.INTEGER },
          },
          {
            tableName: "users",
            sequelize,
          },
        );

我想在这 2 个 table 之间添加一对多关系,所以我添加到 User.ts

PaymentPlan.hasMany(User, {
  foreignKey: 'paymentPlan'
});
User.belongsTo(PaymentPlan);

我运行查询

ALTER TABLE users ADD CONSTRAINT users_FK_1 FOREIGN KEY (paymentPlan) REFERENCES paymentplans(ID) ON DELETE RESTRICT ON UPDATE CASCADE;

用户 table 中的 link paymentPlan 列和 PaymentPlan table 都已完成。 现在当我 运行 例如

await Users.findAll()

那么正在执行的查询是

SELECT `ID`, `name`, `amount`, `fees`, `paymentPlan`,`createdAt`, `updatedAt`, `PaymentPlanID `FROM `users` AS `User`;

当然会抛出错误:

[SequelizeDatabaseError]: Unknown column 'PaymentPlanID' in 'field list'

因为我没有创建 PaymentPlanID 列。我将外键列指定为 paymentPlan。 我究竟做错了什么?如何强制 sequelize 将外键列设置为 'paymentPlan' 而不是创建列 'PaymentPlanID'

您需要在 belongsTo 中指定与您在 hasMany 中相同的外键:

PaymentPlan.hasMany(User, {
  foreignKey: 'paymentPlan'
});
User.belongsTo(PaymentPlan, {
  foreignKey: 'paymentPlan'
});