首页 > 解决方案 > 在 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 来确保在创建所有国家/地区后我将创建活动(这样我确保我不会提及尚未创建的国家/地区)

我在这里能错过什么?

提前致谢,

拉斐尔

标签: reactjspostgresqlexpresspromisesequelize.js

解决方案


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

推荐阅读