Sequelize | 8. 模型 - 獲取器/設(shè)置器/虛擬字段

  1. 獲取器與設(shè)置器是在模型定義時,對數(shù)據(jù)項進(jìn)行輸入與輸出的數(shù)據(jù)處理,一般用于自動填充、格式化輸入輸出等功能。
    數(shù)據(jù)項屬性中的get()方法即獲取器,set(value)方法即設(shè)置器。如下述定義中的first_name數(shù)據(jù)項。
  2. 虛擬字段是在模型定義時,對數(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
  });
})();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容