1. findOne
findOne
方法用于根据条件查找单个记录。如果没有找到符合条件的记录,它将返回 null
。
User.findOne({
where: {
email: 'user@example.com'
}
}).then(user => {
if (user) {
console.log('User found:', user);
} else {
console.log('No user found');
}
});
2. findByPk
findByPk
(Find By Primary Key)方法用于通过主键查找单个记录。你需要提供主键的值。
User.findByPk(1).then(user => {
if (user) {
console.log('User found:', user);
} else {
console.log('No user found');
}
});
3. findAll
findAll
方法用于查找多个记录。你可以使用 where
来指定查询条件,order
来排序结果,limit
和 offset
来分页。
const { Op } = require('sequelize');
User.findAll({
where: {
name: {
[Op.like]: '%John%' // 使用 Sequelize 的 Op 对象进行模糊查询
}
},
order: [
['name', 'ASC'] // 按名字升序排序
],
limit: 10, // 限制结果数量
offset: 0 // 从第0条记录开始
}).then(users => {
console.log('Users found:', users);
});
这里多提一嘴,Op
是一个提供操作符别名的对象。它允许你在查询条件中使用字符串形式的操作符,使得代码更易读和编写。Op
对象包含了一系列常用的操作符,比如 eq
(等于)、ne
(不等于)、gt
(大于)、lt
(小于)、like
(模糊匹配)等。
分页查询:
User.finaAll({
offset: (page - 1) * limit,
limit: +limit,
})
4. count
count
方法用于获取满足特定条件的记录总数。
User.count({
where: {
isActive: true
}
}).then(count => {
console.log('Active users count:', count);
});
findAndCountAll 一边查分页数据,一边查总数。
User.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
})
5. include
include
方法用于实现关联查询,例如当你需要同时获取用户及其关联的帖子时。
首先,定义模型之间的关联:
User.hasMany(Post); // 用户有多个帖子
Post.belongsTo(User); // 帖子属于一个用户
然后,使用 include
在查询中包含关联的数据:
User.findAll({
include: [{
model: Post,
as: 'posts', // 指定别名,用于区分不同的关联
where: {
title: {
[Op.like]: '%Important%' // 只查询标题包含 'Important' 的帖子
}
}
}],
where: {
name: 'John Doe'
}
}).then(users => {
console.log('Users with posts:', users);
});
在这个示例中,我们查询了名字为 “John Doe” 的用户,并且包括了他们拥有的标题包含 “Important” 的帖子。