首页 > 解决方案 > 为什么在 Sequelize 中创建关联模型时使用大写键?

问题描述

我有两个模型 User 和 Post,定义关联模型如下:

Post.belongsTo(models.User)

这意味着 Post 模型属于 User 并且 User 有许多 Post。所以数据库中的posts表必须有这个关联的key userId。

我使用以下代码创建分配给用户的帖子:

Post.create({
    UserId: 1,
})

它会将正确的数据插入数据库。

但这不起作用,因为我更改了代码:

Post.create({
    userId: 1,
})

为什么模型使用大写的 UserId 而不是 userId ?

标签: node.jssequelize.js

解决方案


当您没有在模型上定义列时,将生成关联字段,采用模型名称并Id在末尾添加 。您可以定义小写模型的名称,或定义外部字段,如下所示:

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    //
    userId: { //this is how you are going to use it on sequelize
      field: 'user_id', // this is how is goig to save it on the db, underscore for example
      type: DataTypes.DATE
    },
  });

  Post.associate = (models) => {
    Post.belongsTo(models.User, { as: 'User', foreignKey: 'user_id' });
  };

  return Post;
};

推荐阅读