Sequelize增刪改查及常用介面
阿新 • • 發佈:2020-08-08
一、查詢
查詢分為全部查詢資料,根據條件查詢,全部查詢資料及條數(分頁),查詢特一資料。
1、查詢全部資料
history.findAll().then(function(history) {
console.log(history)
})
2、根據條件查詢資料
其中 OP.or 的意思是滿足下面 dt 和 name 的任意一個都可以,不需要全部滿足。
這個Op是使用以下語句引人入才能夠使用,在很多部落格裡都沒有寫明,需要檢視官方部落格才明瞭:const Op = sequelize.Op;
let data = await history.findAll({ where:{ [Op.or]: [ { dt:{ [Op.like]: `%${crb.dt}%` } }, { name:{ [Op.like]: `%${crb.name}%` } } ] } });
搜尋有多個條件可以供使用:
$and: {a: 5} // AND (a = 5) $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6) $gt: 6, //> 6 $gte: 6, // >= 6 $lt: 10, // < 10 $lte: 10, // <= 10 $ne: 20, // != 20 $eq: 3, // = 3 $not: true, // IS NOT TRUE $between: [6, 10], // BETWEEN 6 AND 10 $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 $in: [1, 2], //IN [1, 2] $notIn: [1, 2], // NOT IN [1, 2] $like: '%hat', // LIKE '%hat' $notLike: '%hat' // NOT LIKE '%hat' $iLike: '%hat' // ILIKE '%hat' (case insensitive) (PG only) $notILike: '%hat' // NOT ILIKE '%hat' (PG only) $like: { $any: ['cat', 'hat']} // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike $overlap: [1, 2] // && [1, 2] (PG array overlap operator) $contains: [1, 2] // @> [1, 2] (PG array contains operator) $contained: [1, 2] // <@ [1, 2] (PG array contained by operator) $any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only) $col: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example
3、根據條件查詢資料及條數(分頁使用)
下面這個語句查詢出來的資料包含了資料總條數,可以用來設定分頁。offset是偏移數,limit為每頁數量
let data = await B.m.db.history.findAndCountAll({ where:{ name:{ [Op.like]:`%${crb.name}%` }, status:{ [Op.in]:crb.status } }, order:[ ['id',crb.sort] ], offset: (crb.currPage - 1) * (crb.pageSize), limit: crb.pageSize, });
返回count為總數,rows為查詢的pageSize list資料
4、查詢特定資料
根據id獲得特定的資料。
let data = await template.findOne({ where:{ id: crb.id } });