reactjs - 在 postgres 上使用 sequelize 创建具有 M:N 关系的实体
问题描述
我基本上有两个主要模型 Country,Activity,它们具有 M:N 关系,所以我使用以下来定义第三个模型 Country_Activity
编辑
Country.belongsToMany(Activity, {through: 'Country_Activity',
foreignKey: 'actId',
otherKey: 'alpha3Code'
})
Activity.belongsToMany(Country, {through: 'Country_Activity',
foreignKey: 'actId',
otherKey: 'alpha3Code'
});
创建所有国家/地区后,我将继续创建活动,但这一次,指示它们所在的国家/地区
router.post('/saveacomplexactivity', async(req, res) => {
console.log('Api::Activities.js (15):: req.body: ', req.body)
await Activity.create({
actId: req.body.actId,
name: req.body.name,
countries: req.body.countries
}, {
include: [Country]
}).then((activity) => {
res.json(activity)
}).catch(err => console.log(err))
})
希望它不仅会创建活动,还会创建联结表 Country_Activity 中的关联
但它不起作用,在创建国家和活动时,创建 Country_Activity 模型但仍然为空
编辑
我收到一个错误,说违反了活动主键唯一性(actId 重复),但很奇怪,因为我只保存一个活动。可能问题出在关系的定义上。
我尝试交换“foreignKey,otherKey”声明,结果相同
我保存到数据库的方式是这样的,首先我将所有国家/地区保存为一个承诺,然后我使用 Promise.All 来确保在创建所有国家/地区后我将创建活动(这样我确保我不会提及尚未创建的国家/地区)
我在这里能错过什么?
提前致谢,
拉斐尔
解决方案
Country.belongsToMany(models.Activity, {
foreignKey: 'countryId',
otherKey: 'activityId',
through: models.Country_Activity,
as: 'activity'
})
Activity.belongsToMany(Country, {
through: 'Country_Activity',
foreignKey: 'countryId',
otherKey: 'activityId',
as: 'country'
});
推荐阅读
- objective-c - iOS 14 崩溃 UITextField 与 textColor = [ UIColor colorWithCIColor: ]
- vue.js - 在 Nuxt 应用程序中使用 Jest 和 Sinon 进行单元测试
- d3.js - 折线图上的阴影效果
- okhttp - 我可以在 OkHttp 中设置 readyAsyncCalls 限制吗?
- sql-server - 根据表和目标中的每个 SQL 语句导出平面文件
- javascript - 替代文件方法
- c++ - 通过引用将指针传递给函数时如何使用与号和星号
- php - 试图从 DB 生态特定日期,但没有显示
- jquery - 如何在点击事件时滚动到jquery中的窗口顶部
- java - Most secure way of storing credentials in a desktop software