How do I set a default value or options of a Foreign Key in a 'BelongsTo' association in Sequelize?

Mic*_*sen 3 sql sequelize.js sequelize-typescript

我在续集方面遇到了一个看似常见的问题。对于上下文,我尝试role为每个user创建的对象分配一个默认值。本质上,每个人的角色都应在首次注册时user设置。default user

我希望能够像使用普通字段一样在模型文件中简单地定义此默认值,但是我似乎找不到正确的语法。

这就是我的用户模型当前的样子:

'use strict';

import { Sequelize } from 'sequelize';

export default (sequelize: Sequelize) => {
  const Users = sequelize.define(
    'Users',
    {
      email: {
        type: Sequelize.STRING,
        allowNull: false
      },
      some_foreign_id: {
        type: Sequelize.STRING,
        allowNull: false
      }
    },
    {}
  );
  Users.associate = models => {
    // associations can be defined here
    Users.belongsTo(models.Roles, { as: 'Role' });
  };
  return Users;
};
Run Code Online (Sandbox Code Playgroud)

目前,我只是进行查询以查找role名称default role并在创建时将其添加到我的用户中。不过我觉得这样的询问是没有必要的。

根据谷歌自动填充建议,似乎很多人都遇到这个问题,但没有任何明确的解决方案。

[编辑]

我的role模型(呵呵)目前看起来像这样:


import { Sequelize } from 'sequelize';

export default (sequelize: Sequelize) => {
  const Roles = sequelize.define(
    'Roles',
    {
      name: {
        type: Sequelize.STRING,
        allowNull: false
      }
    },
    {}
  );
  Roles.associate = models => {
    // associations can be defined here
    // SO note: This association is for my permissions. Should have nothing to do with my User association. 
    Roles.belongsToMany(models.Permissions, { through: 'RolePermission' });
  };
  return Roles;
};
Run Code Online (Sandbox Code Playgroud)

Irf*_*Jip 5

旧答案,请参阅下面更新。

嗯..我现在实际上也有同样的问题,我不知道这是否是一个好的解决方案。但我的模型目前与你的有点相同..

这是我的user模型

// importing sequelize and stuff..

User.init({
  id: {
    type: INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: STRING,
    allowNull: false
  },
  email: {
    type: STRING,
    allowNull: false,
    unique: true,
    validation: {
      isEmail: {
        msg: 'Not a valid email address'
      }
    } 
  },
  password: {
    type: STRING,
    allowNull: false
  },
  RoleId: {
    type: INTEGER,
    allowNull: false,
    defaultValue: 2
  }
}, {/* stuff */})
Run Code Online (Sandbox Code Playgroud)

注意defaultValue中的属性RoleId
现在是我向你们展示我的role 模型的时候了(无意中开玩笑)

Role.init({
  id: {
    type: INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: STRING,
    allowNull: false
  },
  level: {
    type: INTEGER,
    allowNull: false
  }
}, {/* stuff */})
Run Code Online (Sandbox Code Playgroud)

就我而言,当我在控制器POST /login中执行操作时user

// POST /users
  create(req, res) {
    const { name, email, password } = req.body
    return User.create({ name, email, password })
      .then(createdUser => res.json(createdUser))
      .catch(err => res.status(503).json({ msg: err }))
  }
Run Code Online (Sandbox Code Playgroud)

结果如下: 序列化结果

请注意,我只是在尝试一些东西,不知道这个结果是否适用于sequelize. 自从我使用 Sequelize 以来也已经有一段时间了,并注意到他们更改了外键的命名。据我记得以前是这样camelCase,现在是了PascalCase。也许其他人可以帮助解释这些。我的续集版本是5.15.0在我写这篇文章时。

谢谢 :)

哎呀 - 几分钟就更新了..

幸运的是,我在 GitHub 上发现了这个问题:How to require aforeign key to be not null #2837

长话短说

当模型之间关联时,你可以使用这个..

User.belongsTo(Role, {
  foreignKey: {
    /* use this like `sequelize.define(...)` */
    allowNull: false,
    defaultValue: 2
  }
})
Run Code Online (Sandbox Code Playgroud)