简体   繁体   English

Sequelize 在声明关联后创建一个未知列。 奇怪的列的名称模式为“TableNameTableNameId”

[英]Sequelize creates an unknown column after declaring assocations. The weird column has a name pattern of 'TableNameTableNameId'

I have a model declaration of such.我有一个这样的模型声明。

const Account = Sequelize.define("Account", {
   account_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
   }
}

const Student = Sequelize.define("Student", {
   student_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
   },

   account_id: {
      type: DataTypes.INTEGER,
      unique: true,
      allowNull: false,
  }
}

Then I also have declared my associations like然后我也宣布我的协会像

Account.hasOne(models.Student);
Student.belongsTo(models.Account, {
   foreignKey: "account_id",
   allowNull: false,
});

The problem is that when I select the account and join or include the student, in its SQL statement it queries this column with a name of AccountAccountId .问题是,当我选择帐户并加入或include学生时,它在其 SQL 语句中查询名称为AccountAccountId的此列。 This then raises an error that it cannot find that column.然后这会引发一个错误,它找不到该列。

This my query这是我的查询

const account = await Account.findOne({
      attributes: ["account_id", "is_active"],
      include: [
        {
          model: Student,
          attributes: ["student_id", "account_id"],
          where: {
            student_id: id,
          },
        },
      ],
    });

The error is Unknown column 'Student.AccountAccountId' in 'on clause' (errno 1054) (sqlstate 42S22) (CallerID: 0kxatsabmiwg49ko77ez):错误是“on 子句”中的未知列“Student.AccountAccountId”(错误号 1054)(sqlstate 42S22)(来电显示:0kxatsabmiwg49ko77ez):

My package json dependencies:我的包 json 依赖项:

{
"dependencies": {
    "cookie-parser": "^1.4.6",
    "cors": "^2.8.5",
    "csurf": "^1.11.0",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "https": "^1.0.0",
    "jsonwebtoken": "^8.5.1",
    "mysql2": "^2.3.3",
    "passport": "^0.6.0",
    "passport-jwt": "^4.0.0",
    "sequelize": "^6.25.8"
  }
}

This is a typical mistake while defining paired associations: if you indicate a custom foreignKey option with the name of a foreign key column in one association you should indicate the same foreign key name in the second association as well:这是定义成对关联时的一个典型错误:如果您在一个关联中用外键列的名称指示自定义foreignKey选项,您也应该在第二个关联中指示相同的外键名称:

Account.hasOne(models.Student, { foreignKey: "account_id" });
Student.belongsTo(models.Account, {
   foreignKey: "account_id",
   allowNull: false,
});

By default Sequelize gives a name for a foreign key column as: ModelNameId (should be AccountId in this case).默认情况下,Sequelize 为外键列命名为:ModelNameId(在这种情况下应该是AccountId )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM