Sequelize模型关联不会创建新列 [英] Sequelize model association won't create a new column

查看:70
本文介绍了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;
};


这是一个类似的问题:续集未创建模型关联列但!没有回答.


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. 仔细阅读以下内容: https://sequelize.org/master/manual/assocs.html
  2. 进行实验,就像创建一个新的虚拟模型一样,其名称为NewUser.有用!但是同样没有User名称.
  3. 发布在Sequelize的Slack频道上.
  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.

在出现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)
}

Voila,固定!

这篇关于Sequelize模型关联不会创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆