mysql - Sequelize 模型中的自动填充字段?

标签 mysql node.js database model sequelize.js

我正在为 MySQL 中的“用户”表创建模型。理想情况下,我想要一个 'firstName' 和 'lastName' 字段以及一个 'fullName',这将是其他 2 的添加。
是否可以在模型中以编程方式进行处理,或者我是否必须在插入时处理它?

const User = sequelize.define("users", {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  firstName: {
    type: Sequelize.STRING(50),
    allowNull: false,
  },
  lastName: {
    type: Sequelize.STRING(50),
    allowNull: false,
  },
  fullName: {
    type: Sequelize.STRING(50),
    allowNull: false,
    // something that makes 'firstName' + ' ' + 'lastName' ❤️

  },
  email: {
    type: Sequelize.INTEGER(30),
    allowNull: false,
  },
});

最佳答案

虚拟列是您正在寻找的。

"Virtual" columns are columns that do not get saved in your database - they are calculated on the fly based on the values of other columns. They are helpful for saving space if there are values we want to use on our instances that can be easily calculated.

    const User = sequelize.define("users", {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
      },
      firstName: {
        type: Sequelize.STRING(50),
        allowNull: false,
      },
      lastName: {
        type: Sequelize.STRING(50),
        allowNull: false,
      },
       fullName: {
         type: DataTypes.VIRTUAL,
         get() {
               return `${this.firstName} ${this.lastName}`;
         }
      },
      email: {
        type: Sequelize.INTEGER(30),
        allowNull: false,
      },
    });
有关更多信息,请参阅 virtual fields.

关于mysql - Sequelize 模型中的自动填充字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61655553/

相关文章:

database - 使用定期传感器数据设计数据库

database - Laravel 使用数据库 : where does it need to be placed? 在模型中还是在 Controller 中?

mysql - mysql表中匹配字母和数字的模式

MySQL - 获取另一列上具有相同 ID 但不同特定值的行

javascript - 找不到模块包

node.js - 输出对象与关联数据?

mysql - 无法从 vibed 应用程序连接到 MySQL/MariaDB 数据库

mysql - 我在哪里可以找到从 JPA 实体生成的数据库脚本?

javascript - 将 markdown 转换为 json 对象

database - 在用户表中存储用户属性