续集无法通过关联创建



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

例如:

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 创建项目,我不明白如果我只想在 ForeignKey 列中插入和 ID,为什么我需要包含。

我打印了调查:

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;
};

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

尝试更改为:

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

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

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

最新更新