我正在尝试使用现有记录的关联创建记录。
例如:
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;
我收到消息:
users is associated to surveys multiple times. To identify the correct association, you must use the 'as' keyword to specify the alias of the association you want to include.
似乎这就是我在包含中所做的,但它仍然不允许我创建项目。
为什么我不能只用它们的 ID 创建项目,我不明白为什么我需要包含,如果我只想将 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" });
:恕我直言,应该避免使用保留字作为别名 - 这是在自找麻烦。
关于javascript - Sequelize 无法通过关联创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57565267/