Sequelize多对多-如何创建新记录并更新联接表
Sequelize Many to Many - How to create a new record and update join table
我正在用node、express和sequelize构建一个简单的数据库。我已经创建了我的模型,sequelize在我的数据库中创建了表。
我有模型User和City,有很多对很多的关系。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();
在深入研究文档后,我相信我已经找到了答案。
在创建多对多关系时,sequelize会为每个模型创建get、set和add方法。
从假设模型的文档来看,用户和项目具有多对多:http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-许多协会
这将向Project添加方法getUsers、setUsers、addUsers,以及getProjects、setProjects和addProject到User。
因此,在我的案例中,我做了以下操作,其中"城市"是从城市返回的特定城市模型。查找…
//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]);
});
});
一旦创建了City和User模型,就可以创建一个用作联接表的模型的新实例。
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 })
const user = await User.create()
const city = await City.create()
const userCity = await UserCity.create({
userId: user.userId,
cityId: city.cityId,
})
为了补充这个线程中的许多优秀答案,我通常发现,当我有一个实体引用另一个实体时,如果(并且仅当)它还不存在,我想创建被引用的实体。为此,我喜欢使用findOrCreate()
。
所以想象一下,你在存储文章,每一篇文章都可以有任意数量的标签。你通常想做的是:
- 遍历所有需要的标签,并检查它们是否存在。如果它们还不存在,请创建它们
- 一旦找到或创建了所有标签,就创建您的文章
- 创建完文章后,将其链接到步骤1中查找(或创建)的标签
对我来说,这看起来像:
const { article, tags } = model.import("./model/article");
let tagging = [
tags.findOrCreate({where: {title: "big"}}),
tags.findOrCreate({where: {title: "small"}}),
tags.findOrCreate({where: {title: "medium"}}),
tags.findOrCreate({where: {title: "xsmall"}})
];
Promise.all(tagging).then((articleTags)=> {
article.create({
title: "Foo",
body: "Bar"
}).then((articleInstance) => {
articleInstance.setTags(articleTags.map((articleTag) => articleTag[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
相关文章:
- CRM 2011-在插入新记录或修改现有记录时捕获子网格的事件
- jQuery.bind或.on习惯于绑定到新记录
- 如何观察在 Sails .js 中添加到模型中的新记录
- 如何在添加新记录时附加委托
- 添加新记录时删除了 ExtJs 现有记录
- Sequelize多对多-如何创建新记录并更新联接表
- 如何在一个时间间隔后追加新的更新
- 使用新项目更新KendoUI网格数据源
- 使用新值更新时出现数组问题
- 在网页上添加已加载记录的新记录
- 使用Plotly中的新数据更新图形的高性能方法
- MySQL 按行[id]使用新信息更新“n”行数
- 如何使用angularJs/Javascript/Jquery获取表的最后一条记录并更新列值并插入到具有新记录的同一列
- 使用新数据更新 D3 饼图.json
- 使用 Ember-Model 创建新记录
- 级联下拉列表,JSON 不会带来新记录
- 每当有新记录时,使用 Ember-Model 更新视图
- 通过 jQuery 添加新记录元素
- Ember - 绑定到数组控制器中的过滤列表,然后添加新记录
- 当新记录添加到他的存储时,网格没有更新