Sequelize MySQL 处理查询中的本机引用错误 (ManyToMany)

Sequelize MySQL handling native reference errors in Queries (ManyToMany)

我是 MySQL 和 Sequelize 的新手,并尝试为具有引用错误的多对多关系实施错误处理。我有以下关系 Post > CategoryPost < Category 关系。我加入的迁移 Table 看起来像这样

module.exports = {
   up: async (queryInterface, Sequelize) => {

    await queryInterface.createTable("CategoryPost", {
      CategoryId: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        references: {
          model: "categories",
          key: "id",
        },
      },
      PostId: { type: Sequelize.INTEGER, primaryKey: true },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
},

 down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("CategoryPost");
  },
};

根据参考资料,我尝试在加入 table 时避免使用不存在的类别 post。这似乎有效。这是我的 CREATE POST 路由器,包括。控制器。

router.post("/", async (req, res) => {
  let { userUuid, title, body, categories } = req.body;
  if (!categories) {
    return res.status(400).json({ msg: "Pls provide category" });
  }
  try {
    const user = await User.findOne({ where: { uuid: userUuid } });
    const post = await Post.create({
      userId: user.id,
      title,
      body,
    });
    await post.addCategories(categories);
    return res.json(post);
  } catch (err) {
    console.log(err);
    res.status(500).json({ error: "Something went wrong"});
  }
});

它按预期工作。 但是,如果我尝试使用不存在的类别插入 post,我会遇到一个非常丑陋的“本地”mysql 错误,我很难以良好的方式处理它。

我的目标是发送正确的错误消息“请提供 post 有效类别”,如果有未定义的类别

我唯一能想到的就是检查 Category.find(all)。但感觉就像双重实现外键的本机数据库功能并导致额外的请求。

抱歉我的英语不好,我希望问题能清楚。

您的 joining table 应该有自己的主键,与 'Post' 外键和 Category 外键都不相关。这是多对多 table 通常应该工作的一种常见方式。不幸的是,Sequelize 不支持复合主键,因此将 CategoryIdPostId 都指定为主键是没有用的(这绝对可能是第二种方式)。

而且您还忘记将 PostId 指定为 posts 的外键。

await queryInterface.createTable("CategoryPost", {
      Id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      CategoryId: {
        type: Sequelize.INTEGER,
        references: {
          model: "categories",
          key: "id",
        },
      },
      PostId: { type: Sequelize.INTEGER,
        references: {
          model: "posts",
          key: "id",
        },
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
},