請您多多留言指教
此次總結皆在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
}