跳至主要内容
版本:v6 - 稳定版

模型查询 - 查找器

查找器方法是生成SELECT查询的方法。

默认情况下,所有查找器方法的结果都是模型类的实例(而不是简单的 JavaScript 对象)。这意味着数据库返回结果后,Sequelize 会自动将所有内容包装在适当的实例对象中。在某些情况下,如果结果过多,这种包装可能会效率低下。要禁用此包装并改为接收普通响应,请将{ raw: true }作为选项传递给查找器方法。

findAll

findAll方法在之前的教程中已经介绍过。它生成一个标准的SELECT查询,该查询将检索表中的所有条目(除非受where子句等限制)。

findByPk

findByPk方法仅使用提供的 Primary Key 从表中获取单个条目。

const project = await Project.findByPk(123);
if (project === null) {
console.log('Not found!');
} else {
console.log(project instanceof Project); // true
// Its primary key is 123
}

findOne

findOne方法获取它找到的第一个条目(如果提供,则满足可选的查询选项)。

const project = await Project.findOne({ where: { title: 'My Title' } });
if (project === null) {
console.log('Not found!');
} else {
console.log(project instanceof Project); // true
console.log(project.title); // 'My Title'
}

findOrCreate

findOrCreate方法将在表中创建一个条目,除非它能找到一个满足查询选项的条目。在这两种情况下,它都将返回一个实例(找到的实例或创建的实例)以及一个布尔值,指示该实例是创建的还是已经存在。

where选项用于查找条目,defaults选项用于定义在未找到任何条目时必须创建的内容。如果defaults不包含每个列的值,Sequelize 将采用给定给where的值(如果存在)。

假设我们有一个空的数据库,其中有一个User模型,它具有usernamejob

const [user, created] = await User.findOrCreate({
where: { username: 'sdepold' },
defaults: {
job: 'Technical Lead JavaScript',
},
});
console.log(user.username); // 'sdepold'
console.log(user.job); // This may or may not be 'Technical Lead JavaScript'
console.log(created); // The boolean indicating whether this instance was just created
if (created) {
console.log(user.job); // This will certainly be 'Technical Lead JavaScript'
}

findAndCountAll

findAndCountAll方法是一个方便的方法,它结合了findAllcount。这在处理与分页相关的查询时非常有用,在这些查询中,您希望使用limitoffset检索数据,但也需要知道与查询匹配的记录总数。

当未提供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);