sql - Sequelize Many to Many Relationship using Through 不会插入额外的属性
问题描述
Step
我在:和Control
Through之间有多对多的关系ControlsConfig
。在创建Control
对象和调用addStep
函数并指定附加属性(存在于关系表中)时,Sequelize 在关系表中创建记录,ControlsConfig
但附加属性为 NULL。
PS:表在数据库中正确创建。
表 1:步骤
表 2:控制
关系表:ControlsConfig
步
var Step = sequelize.define('Step', {
title: { type: DataTypes.STRING, allowNull: false },
description: DataTypes.STRING,
type: { type: DataTypes.ENUM('task', 'approval'), allowNull: false, defaultValue: 'task' },
order: DataTypes.INTEGER
});
Step.associate = function(models) {
models.Step.belongsTo(models.User);
models.Step.belongsTo(models.Template);
models.Step.hasMany(models.Action);
};
控制
var Control = sequelize.define('Control', {
label: { type: DataTypes.STRING, allowNull: false },
order: { type: DataTypes.INTEGER },
type: { type: DataTypes.ENUM('text', 'yes/no') },
config: { type: DataTypes.TEXT },
controlUiId: { type: DataTypes.STRING }
});
Control.associate = function(models) {
models.Control.belongsTo(models.Section);
};
控制配置
module.exports = (sequelize, DataTypes) => {
var ControlsConfig = sequelize.define('ControlsConfig', {
visibility: { type: DataTypes.ENUM('hidden', 'readonly', 'editable', 'required') },
config: { type: DataTypes.TEXT }
});
ControlsConfig.associate = function(models) {
models.Control.belongsToMany(models.Step, { through: models.ControlsConfig });
models.Step.belongsToMany(models.Control, { through: models.ControlsConfig });
models.ControlsConfig.belongsTo(models.Template);
};
return ControlsConfig;
};
插入:
try {
var step1 = await Step.create({ /*bla bla*/ });
var control1 = await Control.create({ /*bla bla*/ });
var OK = await control1.addStep(step1, {through: { config: 'THIS FIELD ALWAYS APPEARS NULL' }});
} catch (error) { /* No errors*/ }
我遵循文档中所述的相同策略
//If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:
const User = sequelize.define('user', {})
const Project = sequelize.define('project', {})
const UserProjects = sequelize.define('userProjects', {
status: DataTypes.STRING
})
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
//To add a new project to a user and set its status, you pass extra options.through to the setter, which contains the attributes for the join table
user.addProject(project, { through: { status: 'started' }})
解决方案
推荐阅读
- express-gateway - 快递网关 jwt 发行不工作
- python - Pandas - 不同字符串之间的比较总是返回 True
- arrays - Lua 映射值作为构造函数
- python - 如何通过 Python 插入 3d 时间序列数据?
- laravel - Laravel - 如何在当前页面而不是弹出窗口上返回 json
- machine-learning - 定制的留一法交叉验证
- java - 从数据库中获取 Java 流时按行分组
- java - 如何创建稍后可以从列表中实例化的类类型数组?
- sql - 是否可以使用 SQL IN 运算符定位带有文本('9','10')的列?
- c++ - 字符串到 char* 函数