如何在 Sequelize 的 'BelongsTo' 关联中设置外键的默认值或选项?

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

我在使用 sequelize 时遇到了一个看似常见的问题。对于上下文,我试图为每个创建的 user 分配一个默认值 role。基本上每个 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;
};

目前,我正在查询以查找名称为 default rolerole,并在创建时将其添加到我的用户中。但是,我觉得查询是不必要的。

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

[编辑]

我的 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;
};

当您查询用户时,只需执行一个包含

User.find({
  where: {
    id: 1
  },
  include: [{
    model: Role,
    as: 'Role'
  }]
}).then(foundUserWithRole => {
// do something here
}).catch(err => {});

这将 return 每次查询用户时附加到用户的角色。因此,您无需单独查询角色。

您的用户 table 将从关联函数中获取一个 roleId 列。我相信你可以在用户模型中定义 属性 并给它一个默认值 属性.

旧答案,见下方更新。

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

这是我的 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 */})

注意RoleId.
中的defaultValue属性 现在是时候向您展示我的 role 模型(无意的笑话)

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

在我的例子中,当我在我的 user 控制器中执行 POST /login

// 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 }))
  }

结果如下:

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

谢谢:)

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

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

TL;DR

在模型之间进行关联时,您可以使用此..

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