请您多多留言指教
此次总结皆在egg搭建的nodejs框架环境中使用的。
1、两表,三表关联查询(关联表指定非主键字段)
解决:
两表关联引用: foreignKey, sourceKey
三表关联引用:foreignKey 和 otherKey
2、sequelize 默认返回ORM对象格式,理想返回json格式
解决:追加参数 raw: true
3、sequelize model include 包含多个关联表时,git-bash打印SQL会出现子查询,查看SQL不方便,如何去除子查询关联
解决:追加参数 subQuery: false 不使用子查询
4、sequelize findAndCountAll 一对多关联关系查询,默认查询结果返回中的count数量为主表-关联表查询总数量(即主从表关联sql在数据库中返回的数量总和),需求为分页获取总量,则不满足需求(总量非主表数量)。现在需求要结果中的count只返回主表数量,如何处理呢?
例如:学生表student,照片表attachment,一个学生对应10张照片,则student对应10条attachment数据,需求获取student列表并且关联每个学生的照片信息,返回总数量count为学生个数?
现有5个学生,每个学生对应10张照片,如下:
默认:findAndCountAll 返回总数量count为50,然而分页需要返回总数量只是学生的个数5,则解决方式如下:
解决: distinct: true
注:有时解决获取总数量的问题,需要distinct,raw一起使用。
5、配置单个数据源
config.sequelize = {
dialect: 'mysql',
database: 'db_kygk',
host: '127.0.0.1',
port: '3306',
username: 'root',
password: '123456',
dialectOptions: {
compress: true
}
}
6、sequelize 配置多个数据源
引用:
const sequelize = require('sequelize')
const clsNamespace = require('cls-hooked').createNamespace('project_namespace')
sequelize.useCLS(clsNamespace)
config.sequelize = {
Sequelize: sequelize,
datasources: [{
delegate: 'model', // ctx.model
baseDir: 'model',
dialect: 'mysql',
database: 'db_test_1',
host: '127.0.0.1',
port: '3306',
username: 'root',
password: 'password',
}, {
delegate: 'modelPms', // ctx.modelPms
baseDir: 'model-pms',
dialect: 'mysql',
database: 'db_test_2',
host: '127.0.0.1',
port: 3306,
username: 'root',
password: 'password'
}]
}
解释关键词(此配置在nodejs框架中使用):
delegate: 'model', // ctx.model - 授权使用的命名
baseDir: 'model', // 指定文件夹名称
dialect: 'mysql', // 数据库 mysql/oracle等
database: 'db_test_1', // 数据库名
host: '127.0.0.1', // IP
port: '3306', // 端口
username: 'root', // 用户名
password: 'password' // 密码
7、sequelize timezone 时间跨时区设置(东八时区)
解决:设置dialectOptions、timezone
config.sequelize={
dialectOptions:{
// requestTimeout: 60000,
useUTC:false, // for reading from database
dateStrings:true,
typeCast:function(field,next){ // for reading from database
if(field.type==='DATETIME'){
return field.string()
}
return next()
},
},
timezone:'+08:00' // for writing from database
}