Sequelize belongsstomany association:创建一个帖子并关联其现有的标签

时间:2017-02-05 19:16:27

标签: node.js sequelize.js has-and-belongs-to-many

我通过belongsToMany协会获得了两个模型伙伴。

Posts.js:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Posts = sequelize.define('Posts', {
    title: DataTypes.STRING,
    body:  DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        Posts.belongsToMany(models.Tags, {
          through: 'PostsTags',
          as:'posts_has_tags',
          foreignKey:'postId'
        });
      }
    }
  });
  return Posts;
};

和Tags.js:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Tags = sequelize.define('Tags', {
    name: DataTypes.STRING
  },{
    classMethods: {
      associate: function(models) {
        Tags.belongsToMany(models.Posts, {
          through: 'PostsTags',
          as:'posts_has_tags',
          foreignKey:'tagId'
        });
      }
    }
  });
  return Tags;
};

在我的数据库中,我有2个现有标签。 (id:1和id:2) 我在创建帖子时遇到麻烦,我想将其与其中一个标签相关联。

运行此代码:

  create: function(request, reply){
    let post = Object.assign({}, request.payload, request.params);

    models.Posts.create({
        title:  post.title,
        body:   post.body,
        posts_has_tags: [{tagId:1}]
    },{
        include: [{model:models.Tags, as:'posts_has_tags'}]
    }).then(function(newPost){

        if(!newPost){
          return reply('[404] Not found').code(404);
        }
        reply(newPost).code(200);
    })
  }

它运行此查询:

INSERT INTO `Posts` (`id`,`title`,`body`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'TITLE 1','BODY 1','2017-02-05 18:33:21','2017-02-05 18:33:21');

Executing (default): INSERT INTO `Tags` (`id`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'2017-02-05 18:33:21','2017-02-05 18:33:21');

Executing (default): INSERT INTO `PostsTags` (`createdAt`,`updatedAt`,`postId`,`tagId`) VALUES ('2017-02-05 18:33:21','2017-02-05 18:33:21',70,20);
  1. 它创建了一个新帖子,但也是一个我不想要的新标签。
  2. 它在poststags表中创建了关联,但是标签ID不正确(刚创建的那个而不是id 1)
  3. 在promise中如何访问setAssociation()或addAssocation()方法sequelize应该在belongsToMany关联上创建:
  4. 如果我尝试newPost.addTags或newPost.setTags,或者models.Posts.addTags或models.Posts.setTags

    ,我会收到错误或未定义

    如果有人可以帮助我,他会受到欢迎。 我坚持了几天,我想了解如何使用sequelize最好的方式。

1 个答案:

答案 0 :(得分:0)

我更改了别名" as"对于这两种型号:

Posts.js:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Posts = sequelize.define('Posts', {
    title: DataTypes.STRING,
    body:  DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        Posts.belongsToMany(models.Tags, {
          through: 'PostsTags',
          as:'postHasTags',
          foreignKey:'postId'
        });
      }
    }
  });
  return Posts;
};

Tags.js:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Tags = sequelize.define('Tags', {
    name: DataTypes.STRING
  },{
    classMethods: {
      associate: function(models) {
        Tags.belongsToMany(models.Posts, {
          through: 'PostsTags',
          as:'tagHasPosts',
          foreignKey:'tagId'
        });
      }
    }
  });
  return Tags;
};

这两个别名都是相反的。

当我创建新帖子或更新帖子时,我可以访问承诺中由sequelize(model.setAssociation)构建的setter:

upsert: function(request, reply){
    let receivedPost = Object.assign({}, request.payload, request.params);

    models.Posts.find({
      where:{ id:receivedPost.id }
    }).then(post => {
      if(post){
        post.setPostHasTags(receivedPost.tags)
        reply(post).code(200)
      } else {
        models.Posts.create({
            title:  receivedPost.title,
            body:   receivedPost.body
        }).then(newPost => {
            newPost.setPostHasTags(receivedPost.tags)
            reply(newPost).code(200);
        });
      }
    });