[英]Sequelize.js,How to insert a model with one to many to many relationship
[英]Sequelize.js insert a model with one-to-many relationship
我有兩個具有一對多關系的續集模型。 讓我們稱它們為所有者和財產。
假設它們是使用sails-hook-sequelize 定義的(簡化)。
//Owner.js
module.exports = {
options: {
tableName: 'owner'
},
attributes: {
id: {
type: Sequelize.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING(255)
},
associations: function () {
Owner.hasMany(Property, {
foreignKey: {
name: 'owner_id'
}
});
}
}
//Property.js
module.exports = {
options: {
tableName: 'property'
},
attributes: {
id: {
type: Sequelize.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING(255)
}
}
現在假設我想在我的數據庫中插入一個所有者記錄並插入一些與所有者關聯的屬性記錄。 我該怎么做?
我正在尋找類似的東西
Owner.create({name:'nice owner',
property: [{name:'nice property'},
{name:'ugly property'}]});
令人驚訝的是,我在 Sequelize 文檔中找不到這個。
創建所有者時,您不能將財產現有記錄關聯起來,您必須在之后立即使用承諾鏈進行關聯。
Owner.create({name:'nice owner'}).then(function(owner){
owner.setProperties([{name:'nice property'}, {name:'ugly property'}]).then(/*...*/);
});
為了避免這些關聯出現任何問題(所有者創建但某些關聯失敗),最好使用事務。
sequelize.transaction(function(t) {
return Owner.create({name:'nice owner'}, {transaction: t}).then(function(owner){
return owner.setProperties([{name:'nice property'}, {name:'ugly property'}], {transaction : t});
});
});
但是,如果您想創建與新屬性關聯的新所有者,您可以執行以下操作
Owner.create({
name: 'nice owner',
property: [
{ name: 'nice property'},
{ name: 'ugly property'}
]
},{
include: [ Property]
});
請參閱http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.