【问题标题】:Why use the uppercase key when creating association model in Sequelize?为什么在 Sequelize 中创建关联模型时使用大写键?
【发布时间】:2019-03-22 00:51:34
【问题描述】:

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

Post.belongsTo(models.User)

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

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

Post.create({
    UserId: 1,
})

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

但是当我更改代码时它不起作用:

Post.create({
    userId: 1,
})

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

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    当您没有在模型上定义列时,将生成关联字段,采用模型名称并在末尾添加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;
    };
    

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2019-12-12
      • 2021-05-14
      • 1970-01-01
      • 2020-08-25
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多