Ali Hesari
Ali Hesari

Reputation: 1939

The surprising problem in Many-to-many associations using Sequelize

I created three tables posts, tags, and post_tags. Each Post belongs to many Tags through PostTags and each Tags belongs to many Post through PostTag. The surprising problem is when I sort posts.id as DESC the Tags will be empty and the join query result doesn't return any tag. but when I sort id as ASC the tags will be shown in the result JSON. Some of the posts don't have tag. I don't know why this problem is there. If knowing the type of database helps to fix the problem, I use Postgresql.

Models structures are:

// Posts Model
const posts = (sequelize, DataTypes) => {
  const posts = sequelize.define(
    "posts",
    {
      userId: DataTypes.INTEGER,
      title: DataTypes.STRING,
    },
    {
      tableName: "posts",
      timestamps: true,
      paranoid: true
    }
  );

  // Relations
  posts.associate = (models) => {
    posts.belongsToMany(models.tags, {
      through: 'postTags',
      as: 'tags',
      foreignKey: 'postId',
      otherKey: 'tagId'
    });
  }

  return posts;
};

// Tags Model
const tags = sequelize.define(
    "tags",
    {
      title: DataTypes.STRING
    },
    {
      tableName: "tags",
      timestamps: true,
      paranoid: true
    }
  );

  // Relations
  tags.associate = (models) => {
    tags.belongsToMany(models.posts, {
      through: 'postTags',
      as: 'posts',
      foreignKey: 'tagId',
      otherKey: 'postId'
    });
  }

  return tags;
};

// PostTags Model
const post_tags = (sequelize, DataTypes) => {
  const post_tags = sequelize.define(
    "postTags",
    {
      postId: DataTypes.INTEGER,
      tagId: DataTypes.INTEGER
    },
    {
      tableName: "post_tags",
      timestamps: true,
      paranoid: true
    }
  );

  return post_tags;
};

And I selected rows by these options:

const posts = models.posts.findAll({
   attributes: [
     'id',
     'title'
   ],
   include: [
      {
         model: models.tags,
         as: 'tags',
         required: false,
         attributes: [
            'id',
            'title'
         ],
         through: {
            model: models.postTags,
            as: 'postTags',
            attributes: [
               'postId',
               'tagId'
            ]
         }
       }
   ],
   order: [['id', 'desc']]
 });

Upvotes: 1

Views: 165

Answers (1)

Greg Belyea
Greg Belyea

Reputation: 878

Are you logging your sequelize queries to console? I have never had any issue with this, but you may be getting something you don't expect in your query... paste them both into your question if you log them...

Upvotes: 1

Related Questions