简体   繁体   中英

How to insert data into bridging/mapping table using Sequelize.js

I am trying to insert data into the bridging/mapping table using sequelize.js

I defined the Articles as-

const Articles = db.define('article', {
    "slug": {
      type: Sequelize.STRING,
      primaryKey: true,
      allowNull:false
    },
    "title": {
      type: Sequelize.STRING(50),
      allowNull: false
    },
    "description": {
      type: Sequelize.STRING(100),
    },
    "body": Sequelize.STRING,
  })

and Tags as-

const Tags = db.define('tag', {
    name: {
      type: Sequelize.STRING,
      primaryKey: true
    }
})

I created a many-to-many association between them as

Articles.belongsToMany(Tags, {through:'article_tags'})
Tags.belongsToMany(Articles, {through:'article_tags'})

This created a table article_tags in my Database along with articles and tags. But now how can I insert data into this article_tags bridging table using sequelize?

You have to model that mapping table as well.... then when you are in the resolver for say something like "tagArticle" you would just call the create function on the mapping table with the id of the article and the id of the tag... here is an example of a resolver for a join table i have where i am joining Dealers to Accounts

createUserAccountDealer: async (_, args, { models }) => {

      let returnValue = null;
      const { username, input } = args;
      try {
        returnValue = await models.ProfileDealerInfo.create(input);

        if (returnValue && returnValue.dataValues.id) {
          const tempJoin = { username, dealer_id: returnValue.dataValues.id };
          await models.ProfileAccountDealer.create(tempJoin);
        }
      } catch (err) {
        logger.error(err);
      }
      return returnValue;
    }

The difference for me is that dealer is a child of account, so i do the join record right after creating the child dealer record... Your example is a little diff where tags and articles may already exist and you may just only be associating them meaning the id's would just be passed in the args from the client and you would not have the extra step of waiting to get the id back from the child record create

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM