续集多对多 - 如何创建新记录并更新连接表

问题描述:

我正在构建一个包含节点,快速和后续处理的简单数据库。我创建了我的模型,并在我的数据库中创建了表格。续集多对多 - 如何创建新记录并更新连接表

我有模型用户和城市,与多对多的关系。 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

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

创建多对多关系时,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://*.com/questions/29247408/updating-a-many-to-many-join-table-using-sequelize-for-nodejs – wusauarus 2015-03-25 06:17:09

从文档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 

城市和用户模型创建完成后,您可以创建用作连接表的模型的新实例。

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}))