问题
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;
};
This is a similar question: Sequelize not creating model association columns BUT! It wasn't answered.
I've spent hours on this, I did everything like:
- 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 withUsername. - Posted on Sequelize's Slack channel.
After this Stackoverflow question, I will seek help from their Github's issue page.
I'm thinking I can just define the column role_id instead of adding it through the associate function.
回答1:
All models should be registered in one place as long as their associations:
database.js
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const db = {}
const models = path.join(__dirname, 'models') // correct it to path where your model files are
const sequelize = new Sequelize(/* your connection settings here */)
fs
.readdirSync(models)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
.forEach(function (file) {
var model = sequelize['import'](path.join(models, file))
db[model.name] = model
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
db.Sequelize = Sequelize // for accessing static props and functions like Op.or
db.sequelize = sequelize // for accessing connection props and functions like 'query' or 'transaction'
module.exports = db
some_module.js
const db = require('../database')
...
const users = await db.user
.findAll({
where: {
[db.Sequelize.Op.or]: [{
first_name: 'Smith'
}, {
last_name: 'Smith'
}]
}
})
回答2:
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)
in my app.js or server.js. These routes registration was added before the 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)
}
Voila, fixed!
来源:https://stackoverflow.com/questions/61709290/sequelize-model-association-wont-create-a-new-column