Created
March 7, 2017 23:17
-
-
Save mogocat/eb72b5e4c5a7997eb8b4880012888e8d to your computer and use it in GitHub Desktop.
[sequelize模型]#tags:sequelize,model,hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Sequelize = require('sequelize'); | |
var database = require('../model/database'); | |
var moment = require('moment') | |
var Record = require('../model/record'); | |
//定义表的模型 | |
var Business = database.define('business', { | |
id:{ //自增长id,主键,整形 | |
type: Sequelize.INTEGER, | |
primaryKey: true, | |
autoIncrement: true | |
}, | |
stream: { | |
type: Sequelize.INTEGER// 0为入库 1为出库 | |
}, | |
note: { | |
type: Sequelize.INTEGER | |
}, | |
confirm: { | |
type: Sequelize.BOOLEAN, | |
defaultValue: true | |
}, | |
count: { | |
type: Sequelize.VIRTUAL(Sequelize.INTEGER(30), "sum(`records`.count) as count") | |
}, | |
total: { | |
type: Sequelize.VIRTUAL(Sequelize.FLOAT(30), "sum(`records`.price * `records`.count) as total") | |
}, | |
create_at: { | |
type: Sequelize.STRING(20) | |
}, | |
update_at: { | |
type: Sequelize.STRING(20) | |
} | |
}, | |
{ | |
hooks: { | |
beforeCreate: function(business, options){ | |
business.create_at = moment().format('YYYY-MM-DD') | |
return Promise.resolve(business) | |
}, | |
beforeUpdate: function(business, options){ | |
business.update_at = moment().format('YYYY-MM-DD') | |
return Promise.resolve(business) | |
} | |
}, | |
timestamps: false, | |
freezeTableName: true, | |
tableName: 'business' | |
}); | |
Business.hasMany(Record, {foreignKey: 'business_id', constraints: false}); | |
Record.belongsTo(Business, {foreignKey: 'business_id', constraints: false}); | |
module.exports = Business; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment