码迷,mamicode.com
首页 > 其他好文 > 详细

sequelize中model的使用

时间:2019-12-20 20:37:43      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:new   his   get   error   添加   key   校验   create   incr   

/* jshint indent: 2 */
let MD5 = require(‘crypto‘).createHash(‘md5‘);
module.exports = function (sequelize, DataTypes) {
  return sequelize.define(‘Account‘, {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: true,
      // 从数据库查询到数据,经过以下处理后给用户
      get() {
        return "dear " + this.getDataValue(‘name‘);
      }
    },
    age: {
      type: DataTypes.INTEGER(11),
      allowNull: true,

      // 数据校验返回异常 customFunc自定义的校验
      validate: {
        max: {
          args: 100,
          msg: "age is larger"
        },
        min: {
          args: 1, 
          msg: ‘age is small‘
        },
        customFunc(val) {
          if (val === 50) {
            console.log(‘dddd‘);
            throw new Error(‘Only even values are allowed!‘)
          }
        }

      }
    },
    passwd: {
      type: DataTypes.STRING(255),
      allowNull: true,
      // 当插入或者修改时,经过以下处理后再写入数据库
      set(val) {
        val = MD5.update(val).digest(‘hex‘);
        this.setDataValue("passwd", val);
      }

    }
  }, {
    tableName: ‘account‘,

    // setterMethods,getterMethods这个是相当与在存取时都添加了changeName这个虚拟字段
    setterMethods: {
      changeName(val) {
        return this.setDataValue(‘name‘, val.slice(0, -1));
      }
    },
    getterMethods: {
      changeName() {
        return this.name + ‘changeName‘;
      }
    }
  });
};

sequelize中model的使用

标签:new   his   get   error   添加   key   校验   create   incr   

原文地址:https://www.cnblogs.com/tinghaiku/p/12074618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!