【问题标题】:Sequelize belongstomany associations : create a post and associate its existing tagsSequelize belongstomany associations : 创建一个帖子并关联它现有的标签
【发布时间】:2017-02-05 19:16:26
【问题描述】:

我通过 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. 它在 posttags 表中创建关联,但使用错误的标签 id(刚刚创建的而不是 id 1)
  3. 在 promise 中,我如何访问 setAssociation() 或 addAssocation() 方法 sequelize 应该在 belongsToMany 关联上创建:

如果我尝试 newPost.addTags 或 newPost.setTags,或 models.Posts.addTags 或 models.Posts.setTags,我得到错误或未定义

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

【问题讨论】:

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


    【解决方案1】:

    我更改了两个模型的别名“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;
    };
    

    标签.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;
    };
    

    两个别名都颠倒了。

    当我创建一个新帖子或更新一个帖子时,我可以在 promise 中访问由 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);
            });
          }
        });
    

    【讨论】:

    • setPostHasTags 会返回一个 Promise,对吧?您应该在回复之前为其添加 then()。
    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多