请问一下sequelize 多对多关系如何增加和查询数据

code表和tag表是多对多关系

code表 model

'use strict';
module.exports = function(sequelize, DataTypes) {
  var code = sequelize.define('code', {
    markdown: DataTypes.TEXT,
    title:DataTypes.STRING
  }, {
    timestamps: true,
    paranoid: true,
    classMethods: {
      associate: function(models) {
        code.belongsToMany(models['tag'], { through: 'tagcode' })
      }
    }
  });
  return code;
};

tag表 model

'use strict';
module.exports = function(sequelize, DataTypes) {
  var tag = sequelize.define('tag', {
    name: DataTypes.STRING,
  }, {
    timestamps: true,
    paranoid: true,
    classMethods: {
      associate: function(models) {
        tag.belongsToMany(models['code'], { through: 'tagcode' })
      }
    }
  });
  return tag;
};

上面两个model会生成tagcode表。

tag表事先已经有数据。

  dbModels.code.create({
        title: req.body.title,
        markdown: req.body.markdown,
        tags: [
            { name: 'Alpha'},
            { name: 'Beta'}
        ]

    },
        {
        include: {model:dbModels.tag }
        }
    ).then(function (code) {
        res.status(200).json(code)
    })

上面的代码每一次添加code的时候都会添加‘Alpha’‘Beta’ tag。
现在想实现添加code记录的时候传递tagId(多个),然后在关系表tagcode 添加相应的关联,并不在tag表添加数据。
请问一下该如何实现?

阅读 5.3k
3 个回答
 dbModels.code.create({
        title: req.body.title,
        codeCategoryId: req.body.type,
        limit: 1,
        markdown: req.body.markdown,
    }).then(function (code) {
        dbModels.tag.findAll({where: {id: req.body.tags}}).then(function (tags) {
            code.setTags(tags)
            return res.status(200).json({
                message:'添加文章成功'
            })
        })
    })

谢邀,部署sequelize

怎么解决呢??

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题