查询单个数据
findOne
const book = await Book.findOne({
where: {
name: 'JavaScript 高级程序设计'
}
});
if (book) {
console.log(book.toJSON());
} else {
console.log('未找到记录');
}
-
findOne会根据where条件匹配,并返回第一条记录。 -
如果没有匹配,返回
null。
按主键查询单个数据
findByPK
const book = await Book.findByPk(1); // 查询主键为 1 的记录
if (book) {
console.log(book.toJSON());
} else {
console.log('未找到记录');
}
findByPk直接根据主键查询,不需要where条件。- 如果没有匹配,返回
null。
查询多个数据
findAll
示例:
const books = await Book.findAll({
where: {
author: 'Douglas Crockford'
}
});
console.log(books.map(book => book.toJSON()));
findAll会根据where条件返回所有匹配的数据。- 如果没有匹配,返回空数组
[]。
查询数量
count
示例:
javascript
复制编辑
const count = await Book.count({
where: {
author: 'Douglas Crockford'
}
});
console.log(`共有 ${count} 条记录`);
解释:
count只会返回匹配记录的数量。- 如果没有匹配,返回
0。
处理分页有关查询
findAndCountAll
indAndCountAll 方法是结合了 findAll 和 count 的便捷方法. 在处理与分页有关的查询时非常有用,在分页中,你想检索带有 limit 和 offset 的数据,但又需要知道与查询匹配的记录总数.
当没有提供 group 时, findAndCountAll 方法返回一个具有两个属性的对象:
count- 一个整数 - 与查询匹配的记录总数rows- 一个数组对象 - 获得的记录
当提供了 group 时, findAndCountAll 方法返回一个具有两个属性的对象:
count- 一个数组对象 - 包含每组中的合计和预设属性rows- 一个数组对象 - 获得的记录
const { count, rows } = await Project.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
});
console.log(count);
console.log(rows);
示例
exports.getStudents = async function (page = 1, limit = 10){
const results = await Student.findAll({
offset: (page - 1)*limit,
limit:+=limit
});
const total = await Student.count();
const datas = JSON.parse(JSON.stringify(results));
return {
total,
datas
}
};
用findAndCountAl方法:
exports.getStudents = async function (page = 1, limit = 10){
const result = await Student.findAndCountAll({
offset:(page-1)*limit,
limit:+limit,
});
return {
total:result.count,
datas:JSON.parse(JSON.stringify(results));
};
};
加判断条件:
const {Op} = require("sequelize")
exports.getStudents = async function (page = 1, limit = 10,sex = -1,name=""){
const condition ={};
if(sex !==-1){
where.sex = !!sex;
};
if(name){
where.name = {
[Op.like]:`%${name}%`,
};
}
const result = await Student.findAndCountAll({
//限制查询数据
attributes:["id","name","sex","birthday"];
where,
offset:(page-1)*limit,
limit:+limit,
});
return {
total:result.count,
datas:JSON.parse(JSON.stringify(results));
};
};
关联查询(联表查询)
include
用法:
- 用于查询关联模型的数据。
示例:
const books = await Book.findAll({
include: [{
model: Author,
where: { name: 'Douglas Crockford' }
}]
});
console.log(books.map(book => book.toJSON()));
解释:
include用于定义模型之间的关系(如belongsTo、hasMany等)。- 可以在查询时将关联数据一并查询出来。
🔥 总结:
| 方法 | 用法 | 返回值 | 说明 |
|---|---|---|---|
findOne | { where: {...} } | 对象或 null | 查询第一条匹配记录 |
findByPk | (id) | 对象或 null | 按主键查询 |
findAll | { where: {...} } | 数组 | 查询所有匹配记录 |
count | { where: {...} } | 数字 | 统计记录数量 |
include | { include: {...} } | 关联数据对象 | 联表查询 |