Sequelize 模型关联不会创建新列 [英] Sequelize model association won't create a new column
问题描述
为什么在我的某些模型中,sequelize 不会为 foreignkey 创建一个新列?但它确实为其他模型创建???这令人沮丧和奇怪.例如,在这个 User 模型中,sequelize 不会创建 role_id
.
Why is it that in some of my models, sequelize WON’T create a new column for foreignkey? BUT it does create for other models??? It’s frustrating and weird. For instance, in this User model, sequelize won’t create role_id
.
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: { type: DataTypes.BIGINT, allowNull: false, autoIncrement: true, unique: true, primaryKey: true },
first_name: DataTypes.STRING,
last_name: DataTypes.STRING
}, {});
User.associate = function(models) {
User.belongsTo(models.Role, { foreignKey: 'role_id' });
};
return User;
};
<小时>
这是一个类似的问题:Sequelize 不创建模型关联列但是!没有人回答.
我花了几个小时做这件事,我做了以下所有事情:
I've spent hours on this, I did everything like:
- 仔细阅读:https://sequelize.org/master/manual/assocs.html
- 进行实验,例如创建一个名为
NewUser
的新虚拟模型.有用!但同样不是User
名称. - 在 Sequelize 的 Slack 频道上发布.
- Reading this thoroughly: https://sequelize.org/master/manual/assocs.html
- Experimenting, like creating a new dummy model, with name
NewUser
. It works! But again not withUser
name. - Posted on Sequelize's Slack channel.
在这个 Stackoverflow 问题之后,我将向他们的 Github 问题页面寻求帮助.
After this Stackoverflow question, I will seek help from their Github's issue page.
我想我可以只定义列 role_id
而不是通过 associate
函数添加它.
I'm thinking I can just define the column role_id
instead of adding it through the associate
function.
推荐答案
感谢 Anatoly 像这样了解我关于 Sequelize 的问题.
Thanks to Anatoly for keeping up with my questions about Sequelize like this.
经过这么多次试验和错误,我认为问题是由我的路由注册引起的,例如:
After so many trials and errors, I figured that the issue was caused by the registration of my routes like:
require("./app/routes/user/user.routes")(app)
在我的 app.js 或 server.js 中.这些路由注册是在 db.sync
!
in my app.js or server.js. These routes registration was added before the db.sync
!
所以我所做的是,在 db.sync
之后调用这些路由注册,就像这样:
So what I did was, I call these routes registration after that db.sync
, like so:
const db = require("./app/models")
if (process.env.NODE_ENV === "production") {
db.sequelize.sync().then(() => {
useRoutes()
})
} else {
db.sequelize.sync({ force: true }).then(() => {
console.log("Drop and re-sync db.")
useRoutes()
})
}
function useRoutes() {
console.log("Use routes...")
require("./app/routes/user/user.routes")(app)
require("./app/routes/auth/auth.routes")(app)
}
瞧,固定!
这篇关于Sequelize 模型关联不会创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!