如何在 Sequelize 的“BelongsTo"关联中设置外键的默认值或选项? [英] How do I set a default value or options of a Foreign Key in a 'BelongsTo' association in Sequelize?

查看:47
本文介绍了如何在 Sequelize 的“BelongsTo"关联中设置外键的默认值或选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 sequelize 有一个看似常见的问题.对于上下文,我试图为每个创建的 user 分配一个默认的 role.基本上每个 user 的角色应该在第一次注册时设置为 default user.

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

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

'use strict';从续集"导入{续集};导出默认值(续集:续集)=>{const 用户 = sequelize.define('用户',{电子邮件: {类型:Sequelize.STRING,allowNull: 假},some_foreign_id:{类型:Sequelize.STRING,allowNull: 假}},{});Users.associate = 模型 =>{//可以在这里定义关联Users.belongsTo(models.Roles, { as: 'Role' });};返回用户;};

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

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

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

<预><代码>从续集"导入{续集};导出默认值(续集:续集)=>{const 角色 = sequelize.define('角色',{名称: {类型:Sequelize.STRING,allowNull: 假}},{});Roles.associate = 模型 =>{//可以在这里定义关联//所以注意:这个关联是为了我的权限.应该与我的用户关联无关.Roles.belongsToMany(models.Permissions, { through: 'RolePermission' });};返回角色;};

解决方案

旧答案,见下文更新.

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

这是我的user模型

//导入 sequelize 和其他东西..用户.init({ID: {类型:整数,主键:真,自动增量:真},名称: {类型:字符串,allowNull: 假},电子邮件: {类型:字符串,allowNull: 假,独特:真实,验证: {是电子邮件:{msg: '不是有效的电子邮件地址'}}},密码: {类型:字符串,allowNull: 假},角色 ID:{类型:整数,allowNull: 假,默认值:2}}, {/* 东西 */})

注意 RoleId 中的 defaultValue 属性.
现在是我向你展示我的角色模型(无意中的笑话)

Role.init({ID: {类型:整数,主键:真,自动增量:真},名称: {类型:字符串,allowNull: 假},等级: {类型:整数,allowNull: 假}}, {/* 东西 */})

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

//POST/users创建(请求,资源){const { 姓名、电子邮件、密码 } = req.body返回 User.create({ 姓名,电子邮件,密码 }).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空 #2837 .

TL;DR

在模型之间关联时,您可以使用它..

User.belongsTo(Role, {外键:{/* 像 `sequelize.define(...)` 一样使用它 */allowNull: 假,默认值:2}})

I have a seemingly common problem with sequelize. For context I am trying to assign a default role to each user that is created. Essentially each user's role should be set to default user when they are first registered.

I would like to be able to simply define this default value in my Models file as you would with normal fields but, I can't seem to find the correct syntax.

This is what my User model currently looks like:

'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;
};

Currently I am just making a query to find the role with the name default role and adding it to my user as it is created. However, I feel that query is unnecessary.

Based on the google autofill suggestions it seems like a lot of people have this problem without any clear solution.

[EDIT]

My role model (heh) currently looks like this:


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

解决方案

Old Answer, see updated below.

Hm.. I actually have the same problem right now, and I don't know wheter this is a good solution or not. But my models currently a bit the same with yours..

Here is my user model

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

Notice the defaultValue property in RoleId.
And now it is my time to show you my role model (jokes unintended)

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

And in my case, when I do POST /login in my user controller

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

Here is the result:

Bewarned, I was just trying stuff and had no idea if this results are intended in sequelize. It also has been a while since I used Sequelize and notice that they had changed the naming of foreign key. As far as I remember it used to be camelCase, now it's PascalCase. Maybe others can help explaining those. My sequelize version is 5.15.0 at the time I wrote this.

Thank you :)

Whoops - Updated in just a few minutes..

Lucky me, I found this issue on GitHub as How to require a foreign key to be not null #2837 .

TL;DR

When associating between models you can use this..

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

这篇关于如何在 Sequelize 的“BelongsTo"关联中设置外键的默认值或选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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