我目前有一个要关联的用户模型和团队模型。
User.js 模型
"use strict";
module.exports = sequelize => {
const User = sequelize.define(
"User",
{
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true,
allowNull: false
},
...more fields
}
{ tableName: "Users", timestamps: true }
);
User.associate = function(models) {
// 1 to many with skill
User.hasMany(models.Skill, {
foreignKey: "userId"
});
// 1 to many with team
User.hasMany(models.Team, {
foreignKey: "userId"
});
};
return User;
};
Team.js 模型
"use strict";
module.exports = (sequelize, DataTypes) => {
const Team = sequelize.define(
"Team",
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
...more fields
},
{ tableName: "Teams", timestamps: true }
);
Team.associate = function(models) {
Team.belongsTo(models.User, {
foreignKey: "userId"
});
};
return Team;
};
列 userId 会自动添加到具有正确类型 (uuid) 的团队表中,但无论我尝试什么,它始终为空。
我尝试只定义没有选项,然后再次添加了该列,但在创建团队时设置为 null。
1)。定义没有选项的关联。
User.associate = function(models) {
User.hasMany(models.Team);
}
另外,我还有另一个表“技能”,它使用相同的代码但它有效。
"use strict";
module.exports = (sequelize, DataTypes) => {
const Skill = sequelize.define(
"Skill",
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
},
{ tableName: "Skills", timestamps: true }
);
Skill.associate = models => {
Skill.belongsTo(models.User, {
foreignKey: "userId"
});
};
return Skill;
};
这是我用来创建团队的方法。
// Create a new team
exports.createTeam = async (req, res) => {
// Get the user id from the session
const userId = req.session.passport.user.id;
const { title } = req.body;
// Make sure the user hasn't already created a team with that title.
const existingTeam = await models.Team.findOne({
where: { title: title, userId: userId }
});
if (existingTeam !== null) {
// Response and let the user know.
...
return;
}
const defaultTeamValues = {
title: title,
...
};
// No existing team was found with that title and created by that user.
// Create it.
const team = await models.Team.create(defaultTeamValues);
// Done
res.status(200).json(team);
};
团队表中的新记录显示外键 (userId) 列中的空值。
我正在使用 pgAdmin 4 查看表,每个表也有正确的约束 fkeys。
我觉得我在这里遗漏了一些简单的东西,但我已经阅读了文档并搜索了类似的问题,但没有找到我需要的东西。我错过了什么?
最佳答案
好的,所以我有点想通了这个问题。而不是使用
// Look for existing team
const existingTeam = await models.Team.findOne({
where: { title: title, userId: userId }
});
if (existingTeam !== null) {
...
return;
}
// No existing team was found with that title and created by that user.
// Create it.
const team = await models.Team.create(defaultTeamValues);
我切换到这种方法。
const team = await models.Team.findOrCreate({
where: {
title: title,
userId: userId
},
// title and userId will be appended to defaults on create.
defaults: defaultTeamValues
});
不同之处在于 findOrCreate 会将 where 查询中的值附加到您提供的默认值。
这是我之前在添加新技能时所做的,这就是为什么我的技能记录有 userId 而 Teams 没有。
所以在这一点上,我不知道我的关联是否有效,因为我实际上只是将 userId 值添加到新记录中。
回到阅读文档和测试。
关于node.js - 创建新元素时,我的外键始终为空。 Sequelize , Node ,Postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218683/