參考: https://www.cnblogs.com/wuweixin/p/9402125.html
前提: 前端開發負責寫前端頁面以及node開發,node是基於egg.js,node的orm用的是sequelize
例如一個游戲記錄表需要一個關聯一個HxGameGames的表
/**
* 游戲記錄列表
* @param {Object} body 傳入參數
* @param {Object} body.params ...params是除去limit,offset之后剩余的參數
*/
async gameRecord({ limit, offset, ...params }) {
const { rows, count } = await this.ctx.model.HxGameSummaryUserGame.findAndCountAll({
attributes: { exclude: [ 'createdAt', 'updatedAt' ] },
where: {
...params,
},
include: [
{
model: this.app.model.HxGameGames,
as: 'game',
},
],
offset,
limit,
})
return { list: rows, total: count }
}
那么這里include默認的就是內連接
內連接:兩個表都滿足條件的情況下,返回公有數據
左外連接: 左表所有數據,右表匹配不到的數據為null
右外連接:保證右表所有數據,左表匹配不到的數據null填充
假如前端需要實現一個頁面,就是table,里面有很多的字段,在node端的處理就是user主表要關聯baseInfo表,並且在做數據篩選的時候有對baseInfo表的userName進行篩選.不管baseInfo表的數據存在不存在,我需要體現完整的user主表的條數,並且篩選不出問題,那么我們需要做的就是將include變成左外連接,這里用required:false來實現
官方文檔: https://sequelize.org/master/manual/eager-loading.html#referring-to-other-columns
/** 用戶列表導出
* @param { Object } body 查詢條件數據對象
* @param { String } body.userName 用戶名
* @param { Object } body.time 時間
* @return { Object } list用戶列表集合 total當前篩選條件下的記錄總條數
*/
async exportUserList({ userName = '', time, ...params }) {
const { Op } = this.app.Sequelize
const { rows, count } = await this.ctx.model.HxUser.findAndCountAll({
attributes: { exclude: [ 'createdAt', 'updatedAt' ] },
distinct: true,
where: {
...time,
...params,
},
// 如果沒有設置required: false的話 是inner 連接,如果設置了就是左連接
include: [{
model: this.app.model.HxUserBaseInfo,
as: 'basic',
required: !!userName,
where: {
userName: {
[Op.like]: `%${userName}%`,
},
},
},
],
})
return { list: rows, total: count }
}
如果我直接去設置false的話, 那會變成左連接,意思就是假如user表有10數據,不管你怎么篩選,篩選出來的數據永遠都是10條, required: !!userName 表示的就是 userName不存在時就是空,那么就是required: false, 左外連接出現全部的,如果存在的時候,直接內連接,直接篩選userName的數據為准
如果大家有更好的建議,歡迎提出來