MKOA整合了主流ORM框架,提供模型功能。已经支持sequelize及mongoose
本例使用MYSQL数据库
安装相关依赖:
~~~
npm install sequelize --save
#使用mysql
npm install --save mysql
# 如果使用其他数据库选择安装:
npm install --save pg pg-hstore
npm install --save sqlite3
npm install --save tedious // MSSQL
~~~
在开始使用orm数据模型之前,修改config.js配置文件开启
~~~
db_open:true
~~~
添加数据源配置文件datasources.js:
~~~
//数据源定义
module.exports= {
default:{//数据源key
name:'默认数据源',
type:'sequelize',//类型 mongoose 或者 sequelize
prefix:'mkoa_',//数据表前缀 sequelize 源使用
sync:true,//是否同步数据表 sequelize使用 ,为true每次启动会检测是否存在模型数据表,不存在则自动创建
options:{//配置项目
username:'root'
,password:'root'
,database:'Mkoa'
,option:{
dialect:'mysql' //'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql'
,host:'localhost'
,port:3306
}
}
}
};
~~~
> 在test模块下,创建models文件夹,并添加user.js文件:
~~~
/**
* sequelize 模型定义
*/
let DataTypes=require('sequelize');
module.exports ={
// datasources:'default'//模型存储数据源 默认为'default'
// ,name:'user',//模型名称 默认与文件名一致,建议保持默认
model:{ //模型json结构
name:{
type: DataTypes.STRING(40),
allowNull:true,
unique:false,
comment: '昵称/姓名'
}
}
,extend:{//模型扩展部分
tableName:'user',//数据表名,默认与文件名一致
comment: '用户表',
timestamps:true,
indexes:[],
paranoid:false,
charset: 'utf8',
collate: 'utf8_general_ci'
}
,_after:function(){
"use strict";
//数据源所有模型加载后执行,可进行模型关联处理等。
}
};
~~~
extend为sequelize模型特有参数,详细定义配置参考http://docs.sequelizejs.com/en/v3/docs/models-definition/
修改test/controller/index 对模型进行增删改查。
~~~
action['add']= async function () {//新增
"use strict";
let node = await $D('user').create($this.POST);
$this.success(node);
};
action['update']= async function () {//编辑更新
"use strict";
let where = {id:$this.POST['id']};
await $D('user').update($this.POST, {where: where});
$this.success();
};
action['findOne']= async function () {//查找
"use strict";
let node = await $D('user').findById($this.GET['id']);
$this.success(node);
};
action['findAll']= async function (){//所有列表
"use strict";
let perPages=$this.GET['perPages']?$this.GET['perPages']:10;//每页数据数
let currentPage=$this.GET['currentPage']?$this.GET['currentPage']:1;//查询页码
let where = {};//过滤
let res = await $D('user').findAndCountAll({
where: where,
limit: perPages,
offset: perPages * (currentPage - 1)
,raw: true
});
$this.success(res);
};
action['delete']= async function () {//登录
"use strict";
await $D('user').destroy({where:{id:$this.POST['id']}});
$this.success();
};
~~~
说明:
> $D函数,返回模型实例,本例返回sequelize模型实例,具体实例方法参考sequelize使用。sequelize实例返回的是promise支持yield await……
>$this.GET及$this.POST为get方法及post方法提交的数据的一个引用
>$this.success 等价与 $this.body={error:0,data:{}};