Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

javascript - Sequelize model association won't create a new column

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:

  1. Reading this thoroughly: https://sequelize.org/master/manual/assocs.html
  2. Experimenting, like creating a new dummy model, with name NewUser. It works! But again not with User name.
  3. 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'
      }]
     }
})


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...