簡體   English   中英

使用 Sequelize 的多對多關聯中令人驚訝的問題

[英]The surprising problem in Many-to-many associations using Sequelize

我創建了三個表 post、tags 和 post_tags。 每個帖子通過 PostTags 屬於許多標簽,每個標簽通過 PostTag 屬於許多帖子。 令人驚訝的問題是,當我將posts.id排序為DESC ,標簽將為空並且連接查詢結果不返回任何標簽。 但是當我將id排序為ASC ,標簽將顯示在結果 JSON 中。 有些帖子沒有標簽。 我不知道為什么會出現這個問題。 如果知道數據庫的類型有助於解決問題,我使用 Postgresql。

模型結構是:

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

我通過這些選項選擇了行:

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

您是否將 sequelize 查詢記錄到控制台? 我從來沒有遇到過任何問題,但是您可能會在查詢中得到一些您不期望的東西……如果您記錄它們,請將它們粘貼到您的問題中……

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM