跳至主要內容
版本:v6 - 穩定版

模型查詢 - 查找器

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

預設情況下,所有查找器方法的結果都是模型類別的實例(而不是僅僅是普通的 JavaScript 物件)。這表示在資料庫傳回結果後,Sequelize 會自動將所有內容包裝在適當的實例物件中。在少數情況下,當結果太多時,這種包裝可能會效率低下。若要停用此包裝並改為接收純粹的回應,請將 { raw: true } 作為選項傳遞給查找器方法。

findAll

findAll 方法已在先前的教學課程中得知。它會產生標準的 SELECT 查詢,該查詢將擷取表格中的所有項目(除非受到 where 子句之類的條件限制)。

findByPk

findByPk 方法僅使用提供的主要索引鍵從表格中取得單一項目。

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 的值(如果有的話)。

假設我們有一個空的資料庫,其中有一個具有 usernamejobUser 模型。

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);