【问题标题】:Sequelize can't create with associationSequelize 无法通过关联创建
【发布时间】:2023-04-04 23:43:01
【问题描述】:

我正在尝试使用现有记录的关联创建记录。

例如:

        const surveys = await Surveys.create(
          {
            UserToId: args.UserToId,
            UserFromId: args.UserFromId,
            statusId: args.statusId,
            sourceId: args.sourceId,
            link: args.link,
            score: args.score
          },
          {
            include: [
              { model: Users, as: "UseToId" },
              { model: Users, as: "UserFromId" },
              { model: Statuses },
              { model: Sources }
            ]
          }
        );

        console.log("survey:", surveys);
        return surveys;

我收到消息:

用户多次与调查相关联。要识别正确的关联,您必须使用“as”关键字来指定要包含的关联的别名。

这似乎是我在包含中所做的,但它仍然不允许我创建项目。

为什么我不能只用它们的 ID 创建项目,我不明白如果我只想将 ID 插入 ForeignKey 列,为什么我需要包含。

我打印了调查:

dataValues:
   { id: 16,
     statusId: 1,
     sourceId: 1,
     link: 'survey.com/22kj23l',
     score: 4,
     updatedAt: 2019-08-20T00:28:50.511Z,
     createdAt: 2019-08-20T00:28:50.511Z,
     UserToId: null,
     UserFromId: null },
  _previousDataValues:
   { statusId: 1,
     sourceId: 1,
     link: 'survey.com/22kj23l',
     score: 4,
     id: 16,
     createdAt: 2019-08-20T00:28:50.511Z,
     updatedAt: 2019-08-20T00:28:50.511Z,
     toId: undefined,
     fromId: undefined },

我的模型是这样的:

"use strict";
module.exports = (sequelize, DataTypes) => {
  const surveys = sequelize.define(
    "surveys",
    {
      link: DataTypes.STRING,
      score: DataTypes.INTEGER
    },
    {}
  );
  surveys.associate = function(models) {
    // associations can be defined here
    models.surveys.belongsTo(models.statuses);
    models.surveys.belongsTo(models.sources);
    models.surveys.belongsTo(models.users, { as: "to" });
    models.surveys.belongsTo(models.users, { as: "from" });
  };
  return surveys;
};

【问题讨论】:

    标签: javascript postgresql sequelize.js


    【解决方案1】:

    as 值不匹配时发生错误,即“UseToId”“to”。您似乎混淆了表别名和外键字段。

    尝试更改为:

     model.surveys.belongsTo(user, {as: 'toUser', foreignKey: 'UseToId'});
    

    include: [
      { model: Users, as: "toUser" },
    

    关于models.surveys.belongsTo(models.users, { as: "to" });:恕我直言,应避免使用保留字作为别名——这是自找麻烦。

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      相关资源
      最近更新 更多