node.js - 为什么在 Sequelize 中创建关联模型时使用大写键?
问题描述
我有两个模型 User 和 Post,定义关联模型如下:
Post.belongsTo(models.User)
这意味着 Post 模型属于 User 并且 User 有许多 Post。所以数据库中的posts表必须有这个关联的key userId。
我使用以下代码创建分配给用户的帖子:
Post.create({
UserId: 1,
})
它会将正确的数据插入数据库。
但这不起作用,因为我更改了代码:
Post.create({
userId: 1,
})
为什么模型使用大写的 UserId 而不是 userId ?
解决方案
当您没有在模型上定义列时,将生成关联字段,采用模型名称并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;
};
推荐阅读
- angular - 无法使用 angular-oauth2-oidc 使用 Okta 运行 OAuth2
- protractor - 使用 --alternate_cdn 参数更新 webdriver-manager
- c# - 如何在 C# 中动态显示欢迎消息?
- java - 如何在Android上实现平滑渐变?
- python - 在类中使用 numpyarray 时的 Python 内存泄漏
- arm - STM32CubeIDE 中的 CMSIS DSP
- java - ARCore - 从 Modelrenderable 列表中选择不同的 3D 对象
- pandas - 我可以加入两个数据帧,同时只保留基于第二个数据帧中的日期时间的行吗?
- php - 替换第一个 tr PHP pregmatch (REGEX) 中的所有 td
- python - 压缩多个目录中的文件 / FileNotFoundError: [Errno 2] No such file or directory