通过M:N关联创建

时间:2020-03-03 14:19:38

标签: sequelize.js

我正在尝试通过多个表(通过多对多关联)使用findOrCreate,但是我不确定是否可能。我想做的是,在表1中创建一条记录,如果我在表2中找到一条与它们通过正文发送的标签匹配的记录,请选择该记录的ID并在表中创建一条记录3.如果我无法在表2中找到记录,则只需创建它。与表3相同。

但是,我还没有找到一种通过关联(https://sequelize.org/master/manual/creating-with-associations.html#hasmany---belongstomany-association)中提供的方法来实现此目的的方法。

使它起作用的唯一方法是当我这样做时:

const t = await sequelize.transaction();
  try {
    const Testing = await Test.create({'name': body.name},{transaction: t});
    await t.commit();
        for(let j = 0; j < body.tags.length; j++){
            const p = await sequelize.transaction();
            const tagging = await Tag.findOrCreate(
            {
                where: {
                    tag: body.tags[j],
                }, transaction: p,
            });
        await p.commit();
        const f = await sequelize.transaction();
        const tags = await testTagMiddle.findOrCreate(
            {
                where: {
                    test_id: Testing.id,
                    tag_id: tagging[0].id,
                }, transaction: f,
            });
        await f.commit();  
        };
        return res.status(200).json(Testing);
  }catch(err){
        return res.status(418).json({'error': err.toString()});
  }

我也有这些关联:

Tag.belongsToMany(Test, {through: testTagMiddle, foreignKey: 'tag_id'});
Test.belongsToMany(Tag, {through: testTagMiddle, foreignKey: 'test_id'});

我是否正在尝试通过关联来实现?

0 个答案:

没有答案