Skip to content

Association n:m with scope #7153

Closed
Closed

Description

@pola88

Hi everyone,

I have a problem with the following associations:

ItemTag = sequelize.define('item_tag', {
  id : {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  tag_id: {
    type: DataTypes.INTEGER'
  },
  taggable: {
    type: DataTypes.STRING'
  },
  taggable_id: {
    type: DataTypes.INTEGER,
    unique: 'item_tag_taggable'
  }
});

Tag = sequelize.define('tag', {
  name: DataTypes.STRING
});

Post.belongsToMany(Tag, {
  through: {
    model: ItemTag,
    scope: {
      taggable: 'post'
    }
  },
  foreignKey: 'taggable_id'
});

Comment.belongsToMany(Tag, {
  through: {
    model: ItemTag,
    scope: {
      taggable: 'comment'
    }
  },
  foreignKey: 'taggable_id'
});

When I do comment.setTags(tags). It doesn't use the scope to check if the comment already have the tag before insert it again, I mean, uses the next query:

SELECT "taggable_id", "tag_id", "taggable", "created_at", "updated_at" FROM "item_tag" AS "ItemTag" WHERE "ItemTag"."taggable_id" = 1;

It should be:

SELECT "taggable_id", "tag_id", "taggable", "created_at", "updated_at" FROM "item_tag" AS "ItemTag" WHERE "ItemTag"."taggable_id" = 1 AND "ItemTag"."taggable" = 'comment';

What am I doing wrong?

sequelize:  3.21.0
dialect: postgres

Thanks in advance,

Activity

  1. elasticsearcher commented on Jan 27, 2017

    @elasticsearcher
    Contributor

    I have a similar issue when creating a Post with its tags:

    models.Post.create({
      title: 'test',
      tags: [{
        name: 'tag1'
      }]
    }, {
      include: [{
        model: models.Tag,
        as: 'tags',
        through: {
          model: models.ItemTag,
          scope: {
            taggable: 'post'
          }
        }
      }]
    });

    The query that creates the ItemTag row does not pass the taggable field:

    Executing (default): INSERT INTO `posts` (`id`,`title`,`created_at`,`updated_at`) VALUES (DEFAULT,'test','2017-01-27 16:29:15','2017-01-27 16:29:15');
    Executing (default): INSERT INTO `tags` (`id`,`name`,`created_at`,`updated_at`) VALUES (DEFAULT,'tag1','2017-01-27 16:29:15','2017-01-27 16:29:15');
    Executing (default): INSERT INTO `item_tag` (`tag_id`,`taggable_id`,`created_at`,`updated_at`) VALUES (1,1,'2017-01-27 16:29:15','2017-01-27 16:29:15');

    Here are my model definitions:

    // Post
    export
    default
    function(sequelize, DataTypes) {
      var Post = sequelize.define('Post', {
        title: DataTypes.STRING
      }, {
        classMethods: {
          associate: function(models) {
            Post.belongsToMany(models.Tag, {
              as: 'tags',
              foreignKey: 'taggable_id',
              constraints: false,
              through: {
                model: models.ItemTag,
                unique: false,
                scope: {
                  taggable: 'post'
                }
              }
            });
          }
        },
        tableName: 'posts',
        underscored: true
      });
    
      return Post;
    };
    
    
    // Tag
    export
    default
    function(sequelize, DataTypes) {
      var Tag = sequelize.define('Tag', {
        name: DataTypes.STRING,
      }, {
        classMethods: {
          associate: function(models) {
            Tag.belongsToMany(models.Post, {
              as: 'posts',
              foreignKey: 'tag_id',
              constraints: false,
              through: {
                model: models.ItemTag,
                unique: false,
                scope: {
                  taggable: 'posts'
                }
              }
            });
          }
        },
        tableName: 'tags',
        underscored: true
      });
      return Tag;
    };
    
    // ItemTag (the "through" table)
    export
    default
    function(sequelize, DataTypes) {
      var ItemTag = sequelize.define('ItemTag', {
        tag_id: {
          type: DataTypes.INTEGER,
          unique: 'item_tag',
          references: {
            model: 'tags',
            key: 'id'
          }
        },
        taggable_id: {
          type: DataTypes.INTEGER,
          unique: 'item_tag'
        },
        taggable: {
          type: DataTypes.STRING,
          unique: 'item_tag'
        },
      }, {
        classMethods: {
          associate: function(models) {
            ItemTag.belongsTo(models.Post, {
              foreignKey: 'taggable_id',
              constraints: false,
              scope: {
                taggable: 'post'
              }
            });
    
            ItemTag.belongsTo(models.Tag, {
              foreignKey: 'tag_id',
              constraints: false
            });
          }
        },
        tableName: 'item_tag',
        underscored: true
      });
    
      return ItemTag;
    };
  2. elasticsearcher commented on Jan 27, 2017

    @elasticsearcher
    Contributor

    I can confirm @pola88's issue using my model definitions. The SELECT works correctly when using the addTag method, but not when using setTags.

    Promise.all([
      models.Post.create({
        title: 'test 2'
      }),
      models.Tag.create({ name: 'tag1' })
    ]).then(results => {
      const post = results[0],
        tag = results[1];
    
      return post.addTag(tag);
    });

    The above outputs:

    Executing (default): INSERT INTO `posts` (`id`,`title`,`created_at`,`updated_at`) VALUES (DEFAULT,'test 2','2017-01-27 17:37:15','2017-01-27 17:37:15');
    Executing (default): INSERT INTO `tags` (`id`,`name`,`created_at`,`updated_at`) VALUES (DEFAULT,'tag1','2017-01-27 17:37:15','2017-01-27 17:37:15');
    Executing (default): SELECT `tag_id`, `taggable_id`, `taggable`, `created_at`, `updated_at` FROM `item_tag` AS `ItemTag` WHERE `ItemTag`.`taggable_id` = 8 AND `ItemTag`.`tag_id` IN (8) AND `ItemTag`.`taggable` = 'post';
    Executing (default): INSERT INTO `item_tag` (`tag_id`,`taggable_id`,`taggable`,`created_at`,`updated_at`) VALUES (8,8,'post','2017-01-27 17:37:15','2017-01-27 17:37:15');

    Note how the SELECT includes the taggable field in the WHERE clause.

    However, the following code produces the same select but without the taggable field:

    Promise.all([
      models.Post.create({
        title: 'test 2'
      }),
      models.Tag.create({ name: 'tag1' })
    ]).then(results => {
      const post = results[0],
        tag = results[1];
    
      return post.setTags([tag]);
    }).then(console.log);
    Executing (default): INSERT INTO `posts` (`id`,`title`,`created_at`,`updated_at`) VALUES (DEFAULT,'test 2','2017-01-27 17:35:19','2017-01-27 17:35:19');
    Executing (default): INSERT INTO `tags` (`id`,`name`,`created_at`,`updated_at`) VALUES (DEFAULT,'tag1','2017-01-27 17:35:19','2017-01-27 17:35:19');
    Executing (default): SELECT `tag_id`, `taggable_id`, `taggable`, `created_at`, `updated_at` FROM `item_tag` AS `ItemTag` WHERE `ItemTag`.`taggable_id` = 7;
    Executing (default): INSERT INTO `item_tag` (`tag_id`,`taggable_id`,`taggable`,`created_at`,`updated_at`) VALUES (7,7,'post','2017-01-27 17:35:19','2017-01-27 17:35:19');
  3. pola88 commented on Jan 27, 2017

    @pola88
    ContributorAuthor

    Yes, the problem exists when use setAssociations, I checked the code and I saw when they do the select, only include the primaryKey in the where statement.

    https://github.com/sequelize/sequelize/blob/master/lib/associations/belongs-to-many.js#L585

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions