为什么在使用 Sequelize 和 Postgres 发送 POST 请求后我的外键列返回两次?

Why is my foreign key column returned twice after sending a POST request with Sequelize and Postgres?

我有一个唱片(= 专辑)模型和一个艺术家模型,我正在尝试通过 Postman POST 艺术家的唱片到此 URL:http://localhost:3000/api/artists/:artistId/records。 Postgres returns 错误 errorMissingColumnPerhaps you meant to reference the column \"VBRecords.artistId\".(VBRecords 是我所说的 table 以避免内部关键字可能出现的并发症。)

我的服务器记录了以下查询,该查询是在上述 POST 请求上执行的:

Executing (default): INSERT INTO "VBRecords" ("id","title","createdAt","updatedAt","artistId") VALUES (DEFAULT,,,,) RETURNING "id","title","createdAt","updatedAt","ArtistId","artistId";

我相信 ArtistId(RETURNING 块中的倒数第二个参数)是导致问题的原因,但我不知道它的来源。据我了解文档,它不应该在那里,因为最后一个参数 artistId 是正确的,因为它来自参数。

这些是我的模型。我是 Sequelize 的新手,也许模型定义有问题。

models/artist.js

const { Model } = require('sequelize')

module.exports = (sequelize, DataTypes) => {
  class Artist extends Model {
    static associate(models) {
      // removing this association (see UPDATE at the bottom of this post)
      // Artist.hasMany(models.Record, { as: 'records' })
    }
  }

  Artist.init({
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    modelName: 'Artist',
    sequelize,
    tableName: 'VBArtists'
  })

  return Artist
}

models/record.js

const { Model } = require('sequelize')

module.exports = (sequelize, DataTypes) => {
  class Record extends Model {
    static associate(models) {
      Record.belongsTo(models.Artist, {
        foreignKey: 'artistId',
        onDelete: 'CASCADE'
      })
    }
  }

  Record.init({
    title: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    modelName: 'Record',
    sequelize,
    tableName: 'VBRecords'
  })

  return Record
}

感谢任何帮助,如果我可以添加更多代码,请告诉我哪些文件。

提前致谢!

更新:

从艺术家模型中删除 hasMany 关联后,它就可以工作了。但我不明白为什么,甚至 sequelize docs 都说要将两个关联添加到一对多关系中:

Implementation

The main way to do this is as follows:

Team.hasMany(Player); Player.belongsTo(Team);

我通过使用模型内部的那些关联修复了它:

artist.js

const { Model} = require('sequelize')

module.exports = (sequelize, DataTypes) => {
  class Artist extends Model {
    static associate(models) {
      Artist.hasMany(models.Record, {
        foreignKey: 'artistId',
        onDelete: 'CASCADE'
      })
    }
  }

  ...
}

record.js

const { Model } = require('sequelize')

module.exports = (sequelize, DataTypes) => {
  class Record extends Model {
    static associate(models) {
      Record.belongsTo(models.Artist, {
        foreignKey: 'artistId'
      })
    }
  }

  ...
}

我想诀窍是将外键属性添加到两个关联。希望这对以后的人有所帮助。