我正在为 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/