2015-03-03 54 views
5

我正在構建一個包含節點,快速和後續處理的簡單數據庫。我創建了我的模型,並在我的數據庫中創建了表格。續集多對多 - 如何創建新記錄並更新連接表

我有模型用戶和城市,與多對多的關係。 Sequelize創建了表Users,Cities和一個連接表CitiesUsers:帶有UserId和CityId。

我的問題是當我創建一個新用戶時,我該如何更新該連接表? CityId屬性在創建時被忽略。

//Models use 
    //City.hasMany(User); 
    //User.hasMany(City); 

    var user = User.build({ 
     first_name: 'John', 
     last_name: 'Doe', 
     CityId: 5 
    }); 

    user.save(); 
+0

請注意,對於許多一對多的關係,你需要使用'belongsToMany'的關聯:'City.belongsToMany(用戶,通過{:UserCity})' – 2018-03-06 16:59:54

回答

4

在深入研究文檔後,我相信我找到了答案。

創建多對多關係時,sequelize會爲每個模型創建get,set和add方法。

從假設模型的用戶和項目與多對多的文檔: http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-to-many-associations

這將添加方法getUsers,setUsers,ADDUSERS到項目,並 getProjects,setProjects和addProject給用戶。

所以在我的情況下,我做了以下內容,其中 「城市」 是從City.find返回一個特定的城市模型...

//user.setCities([city]); 

models.User.find({ where: {first_name: 'john'} }).on('success', function(user) { 
    models.City.find({where: {id: 10}}).on('success', function(city){ 
    user.setCities([city]); 
    });  
}); 
+0

嘿RickT請你看看我的問題?這非常相似,我想你可能會提供幫助。我真的很感激它。 http://stackoverflow.com/questions/29247408/updating-a-many-to-many-join-table-using-sequelize-for-nodejs – wusauarus 2015-03-25 06:17:09

0

從文檔V3:

// Either by adding a property with the name of the join table model to the object, before creating the association 
project.UserProjects = { 
    status: 'active' 
} 
u.addProject(project) 

// Or by providing a second argument when adding the association, containing the data that should go in the join table 
u.addProject(project, { status: 'active' }) 


// When associating multiple objects, you can combine the two options above. In this case the second argument 
// will be treated as a defaults object, that will be used if no data is provided 
project1.UserProjects = { 
    status: 'inactive' 
} 

u.setProjects([project1, project2], { status: 'active' }) 
// The code above will record inactive for project one, and active for project two in the join table 
0

城市和用戶模型創建完成後,您可以創建用作連接表的模型的新實例。

const User = sequelize.define('user') 
const City = sequelize.define('city') 
const UserCity = sequelize.define('user_city') 

User.belongsToMany(City, { through: UserCity }) 
City.belongsToMany(User, { through: UserCity }) 

Promise.all([User.create(), City.create()]) 
    .then(([user, city]) => UserCity.create({userId: user.id, cityId: city.id}))