【问题标题】:Creating an entity with a M:N relationship with sequelize on postgres在 postgres 上使用 sequelize 创建具有 M:N 关系的实体
【发布时间】:2021-03-07 08:00:45
【问题描述】:

我基本上有两个主要模型 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 来确保在创建所有国家/地区后我将创建活动(这样我可以确保我不会引用尚未创建的国家/地区)

我会在这里遗漏什么?

提前致谢,

拉斐尔

【问题讨论】:

    标签: reactjs postgresql express promise sequelize.js


    【解决方案1】:
    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'
    });
    

    【讨论】:

    • 谢谢你的回答,我一会儿试试
    • countryId, activityId 必须使用 Country_Activity 的属性名称进行数学运算
    • 是否意味着我必须先创建Country-Activity,文档说如果我将'Country_Activity'设置为字符串,它将创建模型。我试过了,还是不行
    • Country_Activity 不是自动创建的
    • 它是自动创建的,我正在检查数据库,文档是这样写的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2018-06-12
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多