我有一个1:m + n:m的关联,但我认为这不会是你的情况的问题。
目前我不知道是否有一个自动功能,但我用这种解决方法。
在我的情况下,它是
重点1:M郎
关键N:M产品
在我创建了一个关键我去的结果,并与所得到的ID新LANGS产生的力矩。
之后,创建密钥与相关产品。
export function create(req, res) {
return DictKey.create(req.body.body)// Create a Key
.then((res)=> {
for (var i = 0; i < req.body.langs.length; i++) {
DictValue.create({//Create Associated Languages
lang_id: req.body.langs[i],
key_id: res._id
})
}
return res;
})
.then((key)=>{
return key.addProduct(req.body.products);//Create Products
})
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
在你的模型定义中,你可以设置默认值,所以你不需要传递任何东西。
'use strict';
export default function(sequelize, DataTypes) {
return sequelize.define('dict_Keys', {
_id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
type: {
type: DataTypes.INTEGER,
allowNull:false,
defaultValue: 0 // DefaultValue if nothing is passed
},
},{
tableName: 'Keys'
});
}
所以你的情况可能是这样的
export default function(sequelize, DataTypes) {
return sequelize.define('UserSettings', {
_id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
YourColumnName: {
type: DataTypes.WhatYouWant,
allowNull:CaseYouNeed,
defaultValue: 0 // DefaultValue if nothing is passed
}
}
export function create(req, res) {
return User.create(req.body)// Create a User
.then((res)=> {
UserSettings.create(
//Create Associated Settings
//send with Values or without which the DefaultValues will handle
)
}
return res;
})
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
我希望这可以帮助你。
谢谢。我正在寻找更多的前/后钩子,每次创建实例时都会这样做。 – akanieski