3

I got two models associates by belongsToMany associations.

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;
};

and 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;
};

In my db i got 2 existing tags. (id:1 and id:2) I got trouble when i create a Post i want to associate it to one of these tags.

By running this code :

  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);
    })
  }

it runs this query :

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. It creates a new post but also a new Tag that i don't want.
  2. It creates the associations in poststags table but with the bad tag id (the one just created instead of the id 1)
  3. In the promise how can i access to the setAssociation() or addAssocation() method sequelize is supposed to create on belongsToMany associations :

I got errors or undefined if i try newPost.addTags or newPost.setTags, or models.Posts.addTags or models.Posts.setTags

If anybody can help me, he's welcome. I stuck on this for days and i'd like to understand right how i can use sequelize the best way.

Deepak
  • 2,487
  • 3
  • 21
  • 27

1 Answers1

0

I changed the alias "as" for both models :

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;
};

Both alias are reversed.

When i create a new post or update one, i can access to the setter built by sequelize (model.setAssociation) in the promise :

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);
        });
      }
    });
Deepak
  • 2,487
  • 3
  • 21
  • 27