模型查询 - 查找器
Finder 方法是生成 SELECT
查询的方法。
¥Finder methods are the ones that generate SELECT
queries.
默认情况下,所有查找器方法的结果都是模型类的实例(而不是简单的 JavaScript 对象)。这意味着数据库返回结果后,Sequelize 会自动将所有内容封装在适当的实例对象中。在某些情况下,当结果太多时,这种封装可能效率低下。要禁用此封装并接收普通响应,请将 { raw: true }
作为选项传递给 finder 方法。
¥By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. In a few cases, when there are too many results, this wrapping can be inefficient. To disable this wrapping and receive a plain response instead, pass { raw: true }
as an option to the finder method.
findAll
findAll
方法从前面的教程中已经知道了。它生成一个标准 SELECT
查询,该查询将从表中检索所有条目(除非受到诸如 where
子句之类的限制)。
¥The findAll
method is already known from the previous tutorial. It generates a standard SELECT
query which will retrieve all entries from the table (unless restricted by something like a where
clause, for example).
findByPk
findByPk
方法使用提供的主键仅从表中获取单个条目。
¥The findByPk
method obtains only a single entry from the table, using the provided 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
方法获取它找到的第一个条目(满足可选查询选项,如果提供的话)。
¥The findOne
method obtains the first entry it finds (that fulfills the optional query options, if provided).
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
将在表中创建一个条目,除非它能找到满足查询选项的条目。在这两种情况下,它将返回一个实例(找到的实例或创建的实例)和一个布尔值,指示该实例是否已创建或已存在。
¥The method findOrCreate
will create an entry in the table unless it can find one fulfilling the query options. In both cases, it will return an instance (either the found instance or the created instance) and a boolean indicating whether that instance was created or already existed.
where
选项用于查找条目,defaults
选项用于定义在未找到任何内容时必须创建的内容。如果 defaults
不包含每列的值,Sequelize 将采用给 where
的值(如果存在)。
¥The where
option is considered for finding the entry, and the defaults
option is used to define what must be created in case nothing was found. If the defaults
do not contain values for every column, Sequelize will take the values given to where
(if present).
假设我们有一个空数据库,其中包含 User
模型,其中包含 username
和 job
。
¥Let's assume we have an empty database with a User
model which has a username
and a job
.
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
方法是结合了 findAll
和 count
的便捷方法。这在处理与分页相关的查询时非常有用,在该查询中你想要使用 limit
和 offset
检索数据,但还需要知道与查询匹配的记录总数。
¥The findAndCountAll
method is a convenience method that combines findAll
and count
. This is useful when dealing with queries related to pagination where you want to retrieve data with a limit
and offset
but also need to know the total number of records that match the query.
当未提供 group
时,findAndCountAll
方法返回一个具有两个属性的对象:
¥When group
is not provided, the findAndCountAll
method returns an object with two properties:
-
count
- 一个整数 - 与查询匹配的记录总数¥
count
- an integer - the total number records matching the query -
rows
- 对象数组 - 获得的记录¥
rows
- an array of objects - the obtained records
当提供 group
时,findAndCountAll
方法返回一个具有两个属性的对象:
¥When group
is provided, the findAndCountAll
method returns an object with two properties:
-
count
- 对象数组 - 包含每组中的计数和投影属性¥
count
- an array of objects - contains the count in each group and the projected attributes -
rows
- 对象数组 - 获得的记录¥
rows
- an array of objects - the obtained records
const { count, rows } = await Project.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%',
},
},
offset: 10,
limit: 2,
});
console.log(count);
console.log(rows);