- 獲取器與設(shè)置器是在模型定義時,對數(shù)據(jù)項進(jìn)行輸入與輸出的數(shù)據(jù)處理,一般用于自動填充、格式化輸入輸出等功能。
數(shù)據(jù)項屬性中的get()方法即獲取器,set(value)方法即設(shè)置器。如下述定義中的first_name數(shù)據(jù)項。
- 虛擬字段是在模型定義時,對數(shù)據(jù)庫字段內(nèi)容進(jìn)行組合或處理后得到的新字段,這個類型的字段不需要存儲在數(shù)據(jù)庫中,一般用于后臺數(shù)據(jù)的填充。
數(shù)據(jù)項屬性中的類型屬性,設(shè)置為DataTypes.VIRTUAL,即可該數(shù)據(jù)項為虛擬字段。如下述定義中的full_name數(shù)據(jù)項。
const { Sequelize, Model, DataTypes } = require('sequelize');
const { Op } = require('sequelize');
const config = require('./config/mysql.config');
const sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: config.dialect,
pool: config.pool
});
class UserModel extends Model { }
UserModel.init({
first_name: {
type: DataTypes.STRING,
get() {
let first_name = this.getDataValue('first_name');
return first_name ? first_name.toUpperCase() : null;
},
set(value) {
let first_name = value ? value.toUpperCase() : null;
this.setDataValue('first_name', first_name);
},
allowNull: false
},
last_name: {
type: DataTypes.STRING,
allowNull: true
},
full_name: {
type: DataTypes.VIRTUAL,
get() {
return `${this.first_name} ${this.last_name}`;
},
set(value) {
throw new Error('Donot set `fullName` value');
}
},
birthday: {
type: DataTypes.DATEONLY,
allowNull: true
},
sex: {
type: DataTypes.ENUM('male', 'female'),
allowNull: true
},
teacher_id: {
type: Sequelize.INTEGER,
references: {
model: 't_teachers',
key: 'id'
}
},
enable: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: true
}
}, {
sequelize,
modelName: 't_users',
freezeTableName: true,
timestamps: false
});
(async () => {
let user_4 = await UserModel.findAll({
where: {
first_name: 'guangming'
}
});
console.log(user_4);
console.log(JSON.stringify(user_4, null, 2));
})();
(async () => {
await UserModel.create({
first_name: 'chen',
last_name: 'chen',
birthday: '2020-05-20',
sex: 'male',
teacher_id: 1,
enable: 1
});
})();