模型
「模型」代表資料庫中的一個表格。此類別的實例代表資料庫的一列。
「模型」實例會使用 dataValues
屬性的概念,該屬性會儲存實例所代表的實際值。預設情況下,也可以直接從「實例」存取 dataValues 中的值,也就是說
instance.field
// is the same as
instance.get('field')
// is the same as
instance.getDataValue('field')
但是,如果為 field
定義了 getter 和/或 setter,則會呼叫它們,而不是從 dataValues
返回值。對於常規用途,最好直接存取屬性或使用 get
,getDataValue
僅應適用於自訂的 getter。
請參閱
- Sequelize#define,以取得有關 getter 和 setter 的更多資訊
靜態方法摘要
靜態公開方法 | ||
公開 靜態 |
為模型新增一個新的作用域。 |
|
公開 靜態 |
async aggregate(attribute: string, aggregateFunction: string, options: object): Promise<DataTypes|object> 在指定的欄位上執行聚合方法 |
|
公開 靜態 |
在這個(來源)和提供的目標之間建立關聯。 |
|
公開 靜態 |
belongsToMany(target: Model, options: object): BelongsToMany 使用聯結表建立 N:M 關聯。 |
|
公開 靜態 |
建立新的模型實例。 |
|
公開 靜態 |
批量建立和插入多個實例。 |
|
公開 靜態 |
計算符合所提供的 where 子句的記錄數量。 |
|
公開 靜態 |
建立新的模型實例並呼叫其儲存方法。 |
|
公開 靜態 |
遞減一或多個欄位的值。 |
自 4.36.0 版本起 |
公開 靜態 |
在資料表上執行描述查詢。 |
|
公開 靜態 |
刪除多個實例,或者如果啟用 |
|
公開 靜態 |
刪除此模型所代表的資料表 |
|
公開 靜態 |
搜尋多個實例。 |
|
公開 靜態 |
async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}> 在指定的偏移/限制內,尋找符合您查詢的所有列,並取得符合您查詢的總列數。 |
|
公開 靜態 |
依據其主鍵搜尋單個實例。 |
|
公開 靜態 |
async findCreateFind(options: object): Promise<Model, boolean> 一個更高效的 findOrCreate,可能無法在交易下運作(在 postgres 中運作)。將執行 find 呼叫,如果為空,則嘗試建立,如果遇到唯一約束,則嘗試再次尋找。 |
|
公開 靜態 |
搜尋單個實例。 |
|
公開 靜態 |
async findOrBuild(options: object): Promise<Model, boolean> 尋找符合查詢的列,如果找不到,則建立(但不儲存)該列。promise 的成功結果將是(實例,已建立)。 |
|
公開 靜態 |
async findOrCreate(options: object): Promise<Model, boolean> 尋找符合查詢的列,如果找不到,則建立並儲存該列。promise 的成功結果將是(實例,已建立)。 |
|
公開 靜態 |
getAttributes(): object | any 傳回模型的屬性。 |
|
公開 靜態 |
getTableName(): string | object 取得模型的資料表名稱,並將綱要納入考量。 |
|
公開 靜態 |
在這個(來源)和提供的目標之間建立 1:m 關聯。 |
|
公開 靜態 |
在這個(來源)和提供的目標之間建立關聯。 |
|
公開 靜態 |
遞增一或多個欄位的值。 |
|
公開 靜態 |
使用屬性和選項初始化模型,表示資料庫中的資料表。 |
|
公開 靜態 |
尋找欄位的最大值 |
|
公開 靜態 |
尋找欄位的最小值 |
|
公開 靜態 |
removeAttribute(attribute: string) 從模型定義中移除屬性 |
|
公開 靜態 |
如果啟用 |
|
公開 靜態 |
將 schema 套用至此模型。 |
|
公開 靜態 |
將在 |
|
公開 靜態 |
尋找欄位的總和 |
|
公開 靜態 |
將此模型同步至資料庫,即建立資料表。 |
|
公開 靜態 |
截斷模型的所有實例。 |
|
公開 靜態 |
取得未設定 scope 的模型 |
|
公開 靜態 |
更新符合 where 選項的多個實例。 |
|
公開 靜態 |
插入或更新單一列。 |
建構子摘要
公開建構子 | ||
public |
constructor(values: object, options: object) 建立新的模型實例。 |
成員摘要
公開成員 | ||
public |
isNewRecord: boolean: * 如果此實例尚未持久化至資料庫,則傳回 true |
|
public get |
對 sequelize 實例的參考 |
方法摘要
公開方法 | ||
public |
如果以字串呼叫 changed,則會傳回布林值,指出 |
|
public |
遞減一或多個欄位的值。 |
|
public |
銷毀對應於此實例的列。 |
|
public |
檢查此實例和 |
|
public |
equalsOneOf(others: Array<Model>): boolean 藉由呼叫 equals 來檢查是否等於 |
|
public |
如果未給定任何鍵,則傳回實例的所有值,也會叫用虛擬 getter。 |
|
public |
getDataValue(key: string): any 取得基礎資料值的值 |
|
public |
遞增一或多個欄位的值。 |
自 4.0.0 起 |
public |
判斷實例是否「軟刪除」的輔助方法。 |
|
public |
從 |
|
public |
就地重新整理目前實例,即 |
|
public |
還原對應於此實例的列。 |
|
public |
驗證此實例,如果驗證通過,則將其持久化至資料庫。 |
|
public |
Set 用於更新實例上的值(實例的 sequelize 表示法,請記住,在您實際呼叫 |
|
public |
setDataValue(key: string, value: any) 更新基礎資料值 |
|
public |
將實例轉換為 JSON 表示法。 |
|
public |
這與呼叫 |
|
public |
根據模型定義中設定的驗證規則,驗證此實例的屬性。 |
|
public |
取得代表此實例查詢的物件,與 |
靜態公開方法
public static addScope(name: string, scope: object | Function, options: object) 原始碼
為模型新增一個新的範圍。當您要包含的模型在定義此模型時不可用時,這對於新增包含的範圍特別有用。
預設情況下,如果已存在具有該名稱的範圍,這將會拋出錯誤。在 options 物件中傳遞 override: true
可關閉此錯誤。
public static async aggregate(attribute: string, aggregateFunction: string, options: object): Promise<DataTypes|object> 原始碼
在指定的欄位上執行聚合方法
參數
名稱 | 類型 | 屬性 | 描述 |
attribute | string | 要彙總的屬性。可以是欄位名稱或 * |
|
aggregateFunction | string | 用於彙總的函數,例如 sum、max 等。 |
|
options | object |
|
查詢選項。請參閱 sequelize.query 了解完整選項 |
options.where | object |
|
搜尋屬性的雜湊。 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.dataType | DataTypes | string |
|
結果的類型。如果 |
options.distinct | boolean |
|
將 DISTINCT 套用到正在彙總的欄位上 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.plain | boolean |
|
當 |
public static belongsTo(target: Model, options: object): BelongsTo 原始碼
在此(來源)和提供的目標之間建立關聯。外來鍵會新增到來源上。
參數
名稱 | 類型 | 屬性 | 描述 |
target | 模型 | 目標模型 |
|
options | object |
|
belongsTo 關聯選項 |
options.hooks | boolean |
|
設定為 true,以便在由於階層式刪除而刪除關聯的模型時執行 before-/afterDestroy 鉤子。例如,如果 |
options.as | string |
|
此模型別名,為單數形式。另請參閱傳遞給 |
options.foreignKey | string | object |
|
來源表格中外來鍵屬性的名稱,或表示外來欄的類型定義的物件(請參閱 |
options.targetKey | string |
|
要用作目標表格中關聯的索引鍵的屬性名稱。預設為目標表格的主索引鍵 |
options.onDelete | string |
|
如果外來鍵允許 null,則設定 NULL,否則設定 NO ACTION |
options.onUpdate | string |
|
設定「ON UPDATE」 |
options.constraints | boolean |
|
是否應在外來鍵上啟用更新和刪除限制。 |
範例
Profile.belongsTo(User) // This will add userId to the profile table
public static belongsToMany(target: Model, options: object): BelongsToMany 原始碼
使用聯結表格建立 N:M 關聯。需要定義 through
。
參數
名稱 | 類型 | 屬性 | 描述 |
target | 模型 | 目標模型 |
|
options | object | belongsToMany 關聯選項 |
|
options.hooks | boolean |
|
設定為 true,以便在由於階層式刪除而刪除關聯的模型時執行 before-/afterDestroy 鉤子。例如,如果 |
options.through | Model | string | object | 用於在 n:m 關聯中聯結來源和目標的表格名稱。如果您想要自行定義聯結表格並將額外屬性新增至其中,也可以是 sequelize 模型。 |
|
options.through.model | 模型 |
|
用於聯結 N:M 關聯兩側的模型。 |
options.through.scope | object |
|
將用於透過模型關聯建立和尋找預設值的鍵/值集合。(請記得將屬性新增至透過模型) |
options.through.unique | boolean |
|
如果為 true,則會從使用的外來鍵產生唯一索引鍵(您可能想要關閉此功能,並在使用範圍時建立特定的唯一索引鍵) |
options.through.paranoid | boolean |
|
如果為 true,則產生的聯結表格將會是偏執的 |
options.as | string | object |
|
此關聯的別名。如果您提供字串,它應該是複數形式,並且會使用 node.inflection 轉換為單數形式。如果您想要自行控制單數版本,請提供具有 |
options.foreignKey | string | object |
|
聯結表格中外來鍵的名稱(代表來源模型),或表示外來欄的類型定義的物件(請參閱 |
options.otherKey | string | object |
|
聯結表格中外來鍵的名稱(代表目標模型),或表示其他欄的類型定義的物件(請參閱 |
options.scope | object |
|
將用於在目標上關聯建立和尋找預設值的鍵/值集合。(sqlite 不支援 N:M) |
options.timestamps | boolean |
|
聯結模型是否應該具有時間戳記 |
options.onDelete | string |
|
如果這是 n:m,則為 Cascade,如果這是 1:m,則為 set null |
options.onUpdate | string |
|
設定 |
options.constraints | boolean |
|
是否應在外來鍵上啟用更新和刪除限制。 |
範例
// Automagically generated join model
User.belongsToMany(Project, { through: 'UserProjects' })
Project.belongsToMany(User, { through: 'UserProjects' })
// Join model with additional attributes
const UserProjects = sequelize.define('UserProjects', {
started: Sequelize.BOOLEAN
})
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
public static async bulkCreate(records: Array, options: object): Promise<Array<Model>> source
批量建立和插入多個實例。
成功處理器會傳遞一個實例陣列,但請注意,這些可能無法完全代表資料庫中資料列的狀態。這是因為 MySQL 和 SQLite 不容易以可對應到多個記錄的方式自動取回自動產生的 ID 和其他預設值。若要取得新建立的值的實例,您需要再次查詢它們。
如果驗證失敗,promise 會以類似陣列的 AggregateError 拒絕。
參數
名稱 | 類型 | 屬性 | 描述 |
records | Array | 要從中建立實例的物件(鍵/值對)清單 |
|
options | object |
|
大量建立選項 |
options.fields | Array |
|
要插入的欄位(預設為所有欄位) |
options.validate | boolean |
|
是否應在插入前對每個資料列進行驗證。如果一個資料列驗證失敗,整個插入作業將會失敗 |
options.hooks | boolean |
|
是否執行大量建立前/後 Hook? |
options.individualHooks | boolean |
|
是否為每個個別實例執行建立前/後 Hook?如果 options.hooks 為 true,仍會執行 BulkCreate Hook。 |
options.ignoreDuplicates | boolean |
|
是否忽略主索引鍵的重複值?(MSSQL 或 Postgres < 9.5 不支援) |
options.updateOnDuplicate | Array |
|
如果資料列鍵已存在,要更新的欄位(在重複鍵更新時)?(僅 MySQL、MariaDB、SQLite >= 3.24.0 和 Postgres >= 9.5 支援)。 |
options.conflictAttributes | Array |
|
查詢的 ON CONFLICT 部分中,衝突欄位的可選覆寫。僅 Postgres >= 9.5 和 SQLite >= 3.24.0 支援 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.returning | boolean | Array |
|
如果為 true,則附加 RETURNING <模型欄位> 以取回所有已定義的值;如果為欄位名稱陣列,則附加 RETURNING <欄位> 以取回特定欄位(僅限 Postgres) |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
public static async count(options: object): Promise<number> source
計算符合所提供的 where 子句的記錄數量。
如果您提供 include
選項,則會改為計算相符關聯的數量。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
options |
options.where | object |
|
搜尋屬性的雜湊。 |
options.include | object |
|
包含選項。請參閱 |
options.paranoid | boolean |
|
設定為 |
options.distinct | boolean |
|
對主索引鍵或 options.col 應用 COUNT(DISTINCT(col))。 |
options.col | string |
|
應套用 COUNT() 的欄位 |
options.attributes | Array |
|
與 |
options.group | Array |
|
用於建立複雜計數。會根據需要傳回多個資料列。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
public static async create(values: object, options: object): Promise<Model> source
建立新的模型實例並呼叫其儲存方法。
參數
名稱 | 類型 | 屬性 | 描述 |
values | object | 要使用其建立新記錄的資料值雜湊 |
|
options | object |
|
建立和查詢選項 |
options.raw | boolean |
|
如果設定為 true,則值會忽略欄位和虛擬設定器。 |
options.isNewRecord | boolean |
|
這是新的記錄嗎? |
options.include | Array |
|
一個包含選項的陣列 - 用於建立預先提取/包含的模型實例。請參閱 |
options.fields | string[] |
|
表示資料庫欄位的可選字串陣列。如果提供欄位,則只會驗證和儲存這些欄位。 |
options.silent | boolean |
|
如果為 true,則不會更新 updatedAt 時間戳記。 |
options.validate | boolean |
|
如果為 false,則不會執行驗證。 |
options.hooks | boolean |
|
執行建立/更新前和更新後的驗證 Hook |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
options.returning | boolean | Array |
|
附加 RETURNING <模型欄位> 以取回所有已定義的值;如果為欄位名稱陣列,則附加 RETURNING <欄位> 以取回特定欄位(僅限 Postgres) |
public static async decrement(fields: string | Array | object, options: object): Promise<Model[], ?number> since 4.36.0 source
減少一或多個欄位的值。此操作在資料庫中執行,這表示它不會使用目前儲存在實例上的值。遞減使用 sql SET column = column - X WHERE foo = 'bar'
查詢來完成。若要在遞減後取得實例中的正確值,您應該重新載入。
範例
Model.decrement('number', { where: { foo: 'bar' });
Model.decrement(['number', 'count'], { by: 2, where: { foo: 'bar' } });
// `by` is ignored, since each column has its own value
Model.decrement({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
public static async destroy(options: object): Promise<number> source
刪除多個實例,或者如果啟用 paranoid
,則將其 deletedAt 時間戳設定為目前時間。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object | 刪除選項 |
|
options.where | object |
|
篩選刪除 |
options.hooks | boolean |
|
是否執行大量刪除前/後 Hook? |
options.individualHooks | boolean |
|
如果設定為 true,則 destroy 將會選取符合 where 參數的所有記錄,並在每個資料列上執行刪除前/後 Hook |
options.limit | number |
|
要刪除的資料列數 |
options.force | boolean |
|
刪除而非將 deletedAt 設定為目前時間戳記(僅當啟用 |
options.truncate | boolean |
|
如果設定為 true,則支援它的方言將使用 TRUNCATE 而非 DELETE FROM。如果截斷資料表,則會忽略 where 和 limit 選項 |
options.cascade | boolean |
|
僅與 TRUNCATE 結合使用。截斷具有指定資料表外鍵參考的所有資料表,或任何由於 CASCADE 而新增至群組的資料表。 |
options.restartIdentity | boolean |
|
僅與 TRUNCATE 結合使用。自動重新啟動截斷資料表欄位所擁有的序列。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
public static async findAll(options: object): Promise<Array<Model>> source
搜尋多個實例。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
描述搜尋範圍的選項雜湊 |
options.where | object |
|
描述搜尋的屬性雜湊。請參閱上方範例。 |
options.attributes | Array<string> | object |
|
您想要選取之屬性的清單,或是包含 |
options.attributes.include | Array<string> |
|
選取模型的所有屬性,以及一些其他屬性。適用於彙總,例如 |
options.attributes.exclude | Array<string> |
|
選取模型的所有屬性,除了少數幾個。這對於安全目的很有用,例如: |
options.paranoid | boolean |
|
如果為 true,則只會返回未刪除的記錄。如果為 false,則會返回已刪除和未刪除的記錄。僅當模型的 |
options.include | Array<object|Model|string> |
|
要使用左連接(left join)急切載入的關聯清單。支援 |
options.include[].model | 模型 |
|
你想要急切載入的模型 |
options.include[].as | string |
|
關聯的別名,在你想要急切載入的模型被別名化時使用。對於 |
options.include[].association | 關聯 |
|
你想要急切載入的關聯。(這可以用來代替提供模型/as 配對) |
options.include[].where | object |
|
要應用於子模型的 Where 子句。請注意,這會將急切載入轉換為內部連接(inner join),除非你明確設定 |
options.include[].or | boolean |
|
是否將 ON 和 WHERE 子句用 OR 而不是 AND 連接在一起。 |
options.include[].on | object |
|
為連接提供你自己的 ON 條件。 |
options.include[].attributes | Array<string> |
|
要從子模型選取的屬性清單 |
options.include[].required | boolean |
|
如果為 true,則轉換為內部連接,這表示只有當父模型有任何符合條件的子模型時才會載入。如果設定了 |
options.include[].right | boolean |
|
如果為 true,並且資料庫方言支援,則轉換為右連接(right join)。如果 |
options.include[].separate | boolean |
|
如果為 true,則執行單獨的查詢來提取關聯的實例,僅支援 hasMany 關聯 |
options.include[].limit | number |
|
限制連接的列數,僅在使用 include.separate=true 時支援 |
options.include[].through.as | string |
|
連接模型的別名,如果你想給它一個與預設名稱不同的名稱。 |
options.include[].through.paranoid | boolean |
|
如果為 true,則只會從連接表返回未刪除的記錄。如果為 false,則會返回已刪除和未刪除的記錄。僅當 through 模型為 paranoid 時才適用。 |
options.include[].through.where | object |
|
針對 belongsToMany 關係,在連接模型上進行篩選 |
options.include[].through.attributes | Array |
|
針對 belongsToMany 關係,要從連接模型選取的屬性清單 |
options.include[].include | Array<object|Model|string> |
|
載入更深層巢狀的相關模型 |
options.include[].duplicating | boolean |
|
將 include 標記為重複的,會防止使用子查詢。 |
options.order | Array | fn | col | literal |
|
指定排序方式。使用陣列,你可以提供多個要排序的欄位/函式。每個元素都可以進一步包裝在一個雙元素陣列中。第一個元素是要排序的欄位/函式,第二個元素是方向。例如: |
options.limit | number |
|
結果的限制 |
options.offset | number |
|
結果的偏移量 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.lock | string | object |
|
鎖定選取的列。可能的選項為 transaction.LOCK.UPDATE 和 transaction.LOCK.SHARE。Postgres 還支援 transaction.LOCK.KEY_SHARE、transaction.LOCK.NO_KEY_UPDATE 以及使用連接的特定模型鎖定。 |
options.skipLocked | boolean |
|
跳過鎖定的列。僅在 Postgres 中支援。 |
options.raw | boolean |
|
返回原始結果。請參閱 sequelize.query 以獲取更多資訊。 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.having | object |
|
Having 選項 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
options.rejectOnEmpty | boolean | Error |
|
當找不到任何記錄時拋出錯誤 |
options.dotNotation | boolean |
|
允許包含具有相同屬性/欄位名稱的表格,這些名稱中帶有點。 |
options.nest | boolean |
|
如果為 true,則將具有 |
範例
Model.findAll({
where: {
attr1: 42,
attr2: 'cake'
}
})
# WHERE attr1 = 42 AND attr2 = 'cake'
const {gt, lte, ne, in: opIn} = Sequelize.Op;
Model.findAll({
where: {
attr1: {
[gt]: 50
},
attr2: {
[lte]: 45
},
attr3: {
[opIn]: [1,2,3]
},
attr4: {
[ne]: 5
}
}
})
# WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5
const {or, and, gt, lt} = Sequelize.Op;
Model.findAll({
where: {
name: 'a project',
[or]: [
{id: [1, 2, 3]},
{
[and]: [
{id: {[gt]: 10}},
{id: {[lt]: 100}}
]
}
]
}
});
# WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`id` > 10 AND `Model`.`id` < 100));
請參閱
- 可能的運算符的運算符 __Alias__: _all_ 如果查詢成功,則 Promise 將解析為模型實例的陣列。
- Sequelize#query
public static async findAndCountAll(options: object): Promise<{count: number|number[], rows: Model[]}> 原始碼
在指定的偏移量/限制內,尋找所有符合查詢的列,並取得符合查詢的總列數。這對於分頁非常有用
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
請參閱 findAll 選項 |
範例
const result = await Model.findAndCountAll({
where: ...,
limit: 12,
offset: 12
});
# In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return the total number of rows that matched your query.
# When you add includes, only those which are required (either because they have a where clause, or because `required` is explicitly set to true on the include) will be added to the count part.
# Suppose you want to find all users who have a profile attached:
User.findAndCountAll({
include: [
{ model: Profile, required: true}
],
limit: 3
});
# Because the include for `Profile` has `required` set it will result in an inner join, and only the users who have a profile will be counted. If we remove `required` from the include, both users with and without profiles will be counted
請參閱
- 關於尋找和查詢選項的規範,請參閱 Model.findAll
- 關於計數選項的規範,請參閱 Model.count
public static async findByPk(param: number | bigint | string | Buffer, options: object): Promise<Model> 原始碼
依據其主鍵搜尋單個實例。
參數
名稱 | 類型 | 屬性 | 描述 |
param | number | bigint | string | Buffer | 所需實例的主鍵值。 |
|
options | object |
|
尋找選項 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
請參閱
- 關於選項的完整說明,請參閱 Model.findAll,請注意,不支援 options.where。
public static async findCreateFind(options: object): Promise<Model, boolean> 原始碼
一個更高效的 findOrCreate,可能無法在交易下運作(在 postgres 中運作)。將執行 find 呼叫,如果為空,則嘗試建立,如果遇到唯一約束,則嘗試再次尋找。
請參閱
- 關於尋找和選項的完整規範,請參閱 Model.findAll
public static async findOne(options: object): Promise<Model|null> 原始碼
搜尋單個實例。返回找到的第一個實例,如果找不到,則返回 null。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
描述搜尋範圍的選項雜湊 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
請參閱
- 關於選項的說明,請參閱 Model.findAll
public static async findOrBuild(options: object): Promise<Model, boolean> 原始碼
尋找符合查詢的列,如果找不到,則建立(但不儲存)該列。promise 的成功結果將是(實例,已建立)。
public static async findOrCreate(options: object): Promise<Model, boolean> 原始碼
尋找符合查詢的列,如果找不到,則建立並儲存該列。promise 的成功結果將是(實例,已建立)。
如果在 options
物件中未傳遞任何交易,則會在內部建立新的交易,以防止在尋找後但在插入呼叫之前,另一個連線建立符合條件的列的競爭條件。但是,並非總是可以在 SQLite 中處理這種情況,特別是如果一個交易插入,而另一個交易嘗試在第一個交易提交之前選取。在這種情況下,將會拋出 sequelize.TimeoutError 的實例。如果建立交易,則會改為建立儲存點,並且將在內部處理任何唯一的約束違規。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object | 尋找和建立選項 |
|
options.where | object | where 搜尋屬性的雜湊。如果 |
|
options.defaults | object |
|
如果要建立新的實例,則使用的預設值 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
請參閱
- 關於尋找和選項的完整規範,請參閱 Model.findAll
public static getTableName(): string | object source
取得模型的資料表名稱,會將 schema 納入考量。如果模型沒有 schema,此方法會以字串形式傳回名稱;否則,會傳回一個具有 tableName
、schema
和 delimiter
屬性的物件。
public static hasMany(target: Model, options: object): HasMany source
在此 (來源) 和提供的目標之間建立一對多的關聯。外鍵會新增至目標。
參數
名稱 | 類型 | 屬性 | 描述 |
target | 模型 | 目標模型 |
|
options | object |
|
hasMany 關聯選項 |
options.hooks | boolean |
|
設定為 true,以便在由於階層式刪除而刪除關聯的模型時執行 before-/afterDestroy 鉤子。例如,如果 |
options.as | string | object |
|
此模型的別名。如果您提供字串,應為複數,並會使用 node.inflection 進行單數化。如果您想要自行控制單數版本,請提供一個具有 |
options.foreignKey | string | object |
|
目標資料表中的外鍵名稱,或代表外鍵欄位類型定義的物件 (請參閱 |
options.sourceKey | string |
|
要在來源資料表中用作關聯鍵的欄位名稱。預設值為來源資料表的主鍵 |
options.scope | object |
|
將用於在目標上關聯建立和尋找預設值的鍵/值集合。(sqlite 不支援 N:M) |
options.onDelete | string |
|
如果 foreignKey 允許 null 值,則為 SET NULL;否則為 CASCADE |
options.onUpdate | string |
|
設定 |
options.constraints | boolean |
|
是否應在外來鍵上啟用更新和刪除限制。 |
範例
User.hasMany(Profile) // This will add userId to the profile table
public static hasOne(target: Model, options: object): HasOne source
在此 (來源) 和提供的目標之間建立關聯。外鍵會新增至目標。
參數
名稱 | 類型 | 屬性 | 描述 |
target | 模型 | 目標模型 |
|
options | object |
|
hasOne 關聯選項 |
options.hooks | boolean |
|
設定為 true,以便在由於階層式刪除而刪除關聯的模型時執行 before-/afterDestroy 鉤子。例如,如果 |
options.as | string |
|
此模型別名,為單數形式。另請參閱傳遞給 |
options.foreignKey | string | object |
|
目標模型中外鍵屬性的名稱,或代表外鍵欄位類型定義的物件 (請參閱 |
options.sourceKey | string |
|
要在來源資料表中用作關聯鍵的屬性名稱。預設值為來源資料表的主鍵 |
options.onDelete | string |
|
如果 foreignKey 允許 null 值,則為 SET NULL;否則為 CASCADE |
options.onUpdate | string |
|
設定「ON UPDATE」 |
options.constraints | boolean |
|
是否應在外來鍵上啟用更新和刪除限制。 |
options.uniqueKey | string |
|
唯一約束的自訂名稱。 |
範例
User.hasOne(Profile) // This will add userId to the profile table
public static async increment(fields: string | Array | object, options: object): Promise<Model[], ?number> source
遞增一個或多個欄位的值。這是在資料庫中完成的,這表示它不使用目前儲存在 Instance 上的值。遞增是使用 SET column = column + X WHERE foo = 'bar'
查詢完成的。若要在遞增到 Instance 後取得正確的值,您應該執行重新載入。
參數
名稱 | 類型 | 屬性 | 描述 |
fields | string | Array | object | 如果提供字串,則該欄會依 options 中給定的 |
|
options | object | 遞增選項 |
|
options.where | object | 條件雜湊 |
|
options.by | number |
|
要遞增的數字 |
options.silent | boolean |
|
如果為 true,則不會更新 updatedAt 時間戳記。 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
範例
Model.increment('number', { where: { foo: 'bar' });
Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
// `by` is ignored, as each column has its own value
Model.increment({ answer: 42, tries: -1}, { by: 2, where: { foo: 'bar' } });
請參閱
public static init(attributes: object, options: object): Model source
使用屬性和選項初始化模型,表示資料庫中的資料表。
資料表欄位是由作為第一個引數提供的雜湊定義。雜湊的每個屬性都代表一個欄位。
參數
名稱 | 類型 | 屬性 | 描述 |
屬性 | object | 一個物件,其中每個屬性都是資料表的欄位。每個欄位可以是 DataType、字串或類型描述物件,具有下列說明的屬性 |
|
attributes.column | string | DataTypes | object | 資料庫欄位的描述 |
|
attributes.column.type | string | DataTypes | 字串或資料類型 |
|
attributes.column.allowNull | boolean |
|
如果為 false,欄位將具有 NOT NULL 約束,並且在儲存執行個體之前將執行非 null 驗證。 |
attributes.column.defaultValue | 任何 |
|
常值預設值、JavaScript 函數或 SQL 函數 (請參閱 |
attributes.column.unique | string | boolean |
|
如果為 true,欄位將取得唯一約束。如果提供字串,欄位將為複合唯一索引的一部分。如果多個欄位具有相同的字串,它們將為相同唯一索引的一部分 |
attributes.column.primaryKey | boolean |
|
如果為 true,此屬性將標記為主鍵 |
attributes.column.field | string |
|
如果已設定,sequelize 會將屬性名稱對應到資料庫中的不同名稱 |
attributes.column.autoIncrement | boolean |
|
如果為 true,此欄位將設定為自動遞增 |
attributes.column.autoIncrementIdentity | boolean |
|
如果為 true,搭配 autoIncrement=true,將使用 Postgres |
attributes.column.comment | string |
|
此欄位的註解 |
attributes.column.references | string | Model |
|
具有參考組態的物件 |
attributes.column.references.model | string | Model |
|
如果此欄位參考另一個資料表,請在此處以模型或字串形式提供 |
attributes.column.references.key | string |
|
此欄位參考的外來資料表的欄位 |
attributes.column.onUpdate | string |
|
在更新參考鍵時應該發生的情況。選項之一為 CASCADE、RESTRICT、SET DEFAULT、SET NULL 或 NO ACTION |
attributes.column.onDelete | string |
|
在刪除參考鍵時應該發生的情況。選項之一為 CASCADE、RESTRICT、SET DEFAULT、SET NULL 或 NO ACTION |
attributes.column.get | Function |
|
為此欄位提供自訂 getter。使用 |
attributes.column.set | Function |
|
為此欄位提供自訂 setter。使用 |
attributes.column.validate | object |
|
每次儲存模型時,為此欄位執行驗證的物件。可以是 validator.js 提供的驗證名稱、透過擴充 validator.js 提供的驗證函數 (請參閱 |
options | object | 這些選項會與提供給 Sequelize 建構函式的預設定義選項合併 |
|
options.sequelize | object | 定義要附加至新模型的 sequelize 執行個體。如果未提供,則擲回錯誤。 |
|
options.modelName | string |
|
設定模型的名稱。預設情況下,它與類別名稱相同。 |
options.defaultScope | object |
|
定義要用於此模型的預設搜尋範圍。範圍的形式與傳遞給 find/findAll 的選項相同 |
options.scopes | object |
|
更多範圍,以與上述 defaultScope 相同的方式定義。如需有關範圍如何定義以及如何使用它們的更多資訊,請參閱 |
options.omitNull | boolean |
|
不要持久化 null 值。這表示將不會儲存所有具有 null 值的欄位 |
options.timestamps | boolean |
|
將 createdAt 和 updatedAt 時間戳記新增至模型。 |
options.paranoid | boolean |
|
如果此選項為 true,呼叫 |
options.underscored | boolean |
|
將底線欄位新增至所有屬性,這涵蓋使用者定義的屬性、時間戳記和外鍵。將不會影響明確設定 |
options.freezeTableName | boolean |
|
如果 freezeTableName 為 true,sequelize 將不會嘗試更改模型名稱來取得資料表名稱。否則,模型名稱將會被複數化。 |
options.name | object |
|
一個具有兩個屬性的物件, |
options.name.singular | string |
|
模型的單數名稱 |
options.name.plural | string |
|
模型的複數名稱 |
options.indexes | 陣列<物件> |
|
索引定義 |
options.indexes[].name | string |
|
索引的名稱。預設為模型名稱 + _ + 串聯的欄位 |
options.indexes[].type | string |
|
索引類型。僅由 mysql 使用。為 |
options.indexes[].using | string |
|
建立索引的方法(SQL 中的 |
options.indexes[].operator | string |
|
指定索引運算子。 |
options.indexes[].unique | boolean |
|
索引是否應為唯一?也可以通過將類型設定為 |
options.indexes[].concurrently | boolean |
|
PostgresSQL 將在不取得任何寫入鎖定的情況下建立索引。僅限 Postgres |
options.indexes[].fields | 陣列<字串|物件> |
|
要建立索引的欄位陣列。每個欄位可以是包含欄位名稱的字串、sequelize 物件(例如 |
options.createdAt | string | boolean |
|
如果提供字串,則覆寫 createdAt 屬性的名稱,如果為 false,則停用它。Timestamps 必須為 true。帶底線的欄位將使用帶底線的設定。 |
options.updatedAt | string | boolean |
|
如果提供字串,則覆寫 updatedAt 屬性的名稱,如果為 false,則停用它。Timestamps 必須為 true。帶底線的欄位將使用帶底線的設定。 |
options.deletedAt | string | boolean |
|
如果提供字串,則覆寫 deletedAt 屬性的名稱,如果為 false,則停用它。Timestamps 必須為 true。帶底線的欄位將使用帶底線的設定。 |
options.tableName | string |
|
預設為複數化的模型名稱,除非 freezeTableName 為 true,在這種情況下,它將逐字使用模型名稱 |
options.schema | string |
|
schema |
options.engine | string |
|
指定模型資料表的引擎 |
options.charset | string |
|
指定模型資料表的字元集 |
options.comment | string |
|
指定模型資料表的註解 |
options.collate | string |
|
指定模型資料表的校對 |
options.initialAutoIncrement | string |
|
設定 MySQL 中資料表的初始 AUTO_INCREMENT 值。 |
options.hooks | object |
|
在某些生命週期事件之前和之後呼叫的 hook 函數的物件。可能的 hook 有:beforeValidate、afterValidate、validationFailed、beforeBulkCreate、beforeBulkDestroy、beforeBulkUpdate、beforeCreate、beforeDestroy、beforeUpdate、afterCreate、beforeSave、afterDestroy、afterUpdate、afterBulkCreate、afterSave、afterBulkDestroy 和 afterBulkUpdate。有關 hook 函數及其簽章的詳細資訊,請參閱 Hooks。每個屬性可以是函數或函數陣列。 |
options.validate | object |
|
模型範圍驗證的物件。驗證可以透過 |
options.whereMergeStrategy | 'and' | 'overwrite' |
|
指定範圍合併策略(預設為 'overwrite')。'and' 策略將透過在最頂層新增 |
範例
Project.init({
columnA: {
type: Sequelize.BOOLEAN,
validate: {
is: ['[a-z]','i'], // will only allow letters
max: 23, // only allow values <= 23
isIn: {
args: [['en', 'zh']],
msg: "Must be English or Chinese"
}
},
field: 'column_a'
// Other attributes here
},
columnB: Sequelize.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
}, {sequelize})
sequelize.models.modelName // The model will now be available in models under the class name
public static async restore(options: 物件): Promise 來源
如果啟用 paranoid
,則還原多個實例。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object | 還原選項 |
|
options.where | object |
|
篩選還原 |
options.hooks | boolean |
|
執行批量還原 hook 之前/之後? |
options.individualHooks | boolean |
|
如果設定為 true,還原將在 where 參數中找到所有記錄,並在每行上執行 bulkRestore hook 之前/之後 |
options.limit | number |
|
要取消刪除多少列(僅限 mysql) |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
public static schema(schema: 字串, options: 物件): 模型 來源
將 schema 套用到此模型。對於 postgres,這實際上會將 schema 放在資料表名稱之前 - "schema"."tableName"
,而對於 mysql 和 sqlite,schema 會附加到資料表名稱 - 'schema.tablename'
。
此方法適用於在多個 schema 中需要相同模型的情況。在這種情況下,請務必針對每個模型呼叫 model.schema(schema, [options]).sync()
,以確保在正確的 schema 中建立模型。
如果每個模型需要單一預設 schema,請在模型的 define()
呼叫期間設定 options.schema='schema'
參數。
請參閱
- 有關設定預設 schema 的詳細資訊,請參閱 Sequelize#define。
public static scope(option: 陣列 | 物件 | 字串): 模型 來源
將在 define
中建立的 scope 套用至模型。
範例
const Model = sequelize.define('model', attributes, {
defaultScope: {
where: {
username: 'dan'
},
limit: 12
},
scopes: {
isALie: {
where: {
stuff: 'cake'
}
},
complexFunction: function(email, accessLevel) {
return {
where: {
email: {
[Op.like]: email
},
access_level {
[Op.gte]: accessLevel
}
}
}
}
}
})
# As you have defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:
Model.findAll() // WHERE username = 'dan'
Model.findAll({ where: { age: { [Op.gt]: 12 } } }) // WHERE age > 12 AND username = 'dan'
Model.scope({ method: ['complexFunction', '[email protected]', 42]}).findAll()
// WHERE email like '[email protected]%' AND access_level >= 42
public static async sync(options: object): Promise<Model> source
將此模型同步至資料庫,即建立資料表。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
同步選項 |
請參閱
- 選項請參閱 Sequelize#sync
public static async truncate(options: object): Promise source
截斷模型的所有實例。這是 Model.destroy({ truncate: true }) 的便捷方法。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
傳遞給 Model.destroy 除了 truncate 以外的選項 |
options.cascade | boolean | Function |
|
截斷所有具有外鍵參考到指定表格的表格,或因 CASCADE 而加入群組的任何表格。 |
options.restartIdentity | boolean |
|
自動重新啟動被截斷表格的欄位所擁有的序列。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.logging | boolean | Function |
|
記錄 SQL 查詢的函式,若為 false 則不記錄 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
請參閱
- 更多資訊請參閱 Model.destroy
public static async update(values: object, options: object): Promise<Array<number, number>> source
更新符合 where 選項的多個實例。
參數
名稱 | 類型 | 屬性 | 描述 |
values | object | 要更新的值的雜湊 |
|
options | object | 更新選項 |
|
options.where | object | 描述搜尋範圍的選項。 |
|
options.paranoid | boolean |
|
如果為 true,則只會更新未刪除的記錄。如果為 false,則會更新已刪除和未刪除的記錄。僅當模型的 `options.paranoid` 為 true 時才適用。 |
options.fields | Array |
|
要更新的欄位(預設為所有欄位) |
options.validate | boolean |
|
是否應在插入前對每個資料列進行驗證。如果一個資料列驗證失敗,整個插入作業將會失敗 |
options.hooks | boolean |
|
執行批量更新前後的 hooks 嗎? |
options.sideEffects | boolean |
|
是否更新任何虛擬 setter 的副作用。 |
options.individualHooks | boolean |
|
執行更新前後的 hooks 嗎?如果為 true,則會執行 SELECT,然後執行個別的 UPDATE。需要 SELECT,因為需要將列資料傳遞給 hooks |
options.returning | boolean | Array |
|
如果為 true,則附加 RETURNING <模型欄位> 以取回所有已定義的值;如果為欄位名稱陣列,則附加 RETURNING <欄位> 以取回特定欄位(僅限 Postgres) |
options.limit | number |
|
要更新的列數 (僅適用於 mysql 和 mariadb,對於 MSSQL 實作為 TOP(n);對於 sqlite,僅當存在 rowid 時才支援) |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.silent | boolean |
|
如果為 true,則不會更新 updatedAt 時間戳記。 |
public static async upsert(values: object, options: object): Promise<Array<Model, boolean|null>> source
插入或更新單一列。如果找到符合主鍵或唯一鍵的供應值之列,則將執行更新。請注意,唯一索引必須在您的 sequelize 模型中定義,而不僅僅是在表格中定義。否則,您可能會遇到唯一約束違規,因為 sequelize 無法識別應更新的列。
實作細節
- MySQL - 使用 ON DUPLICATE KEY UPDATE 實作
- PostgreSQL - 使用 ON CONFLICT DO UPDATE 實作。如果更新資料包含 PK 欄位,則 PK 會被選為預設的衝突鍵。否則,將選取第一個可以滿足衝突鍵需求的唯一約束/索引。
- SQLite - 使用 ON CONFLICT DO UPDATE 實作
- MSSQL - 使用
MERGE
和WHEN (NOT) MATCHED THEN
實作為單一查詢
請注意,無論列是建立或更新,Postgres/SQLite 都會回傳 null 作為建立的結果
參數
名稱 | 類型 | 屬性 | 描述 |
values | object | 要 upsert 的值的雜湊 |
|
options | object |
|
upsert 選項 |
options.validate | boolean |
|
在插入列之前執行驗證 |
options.fields | Array |
|
如果記錄已存在,則要更新的欄位。預設為所有已變更的欄位。如果所提供的 `values` 物件中沒有指定欄位,則仍會嘗試插入,但會忽略重複鍵衝突。 |
options.hooks | boolean |
|
執行 upsert 前後的 hooks 嗎? |
options.returning | boolean |
|
如果為 true,則取回自動產生值 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.benchmark | boolean |
|
將查詢執行時間(以毫秒為單位)作為第二個引數傳遞給記錄函數 (options.logging)。 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
options.conflictFields | Array<string> |
|
查詢的 ON CONFLICT 部分中,衝突欄位的可選覆寫。僅 Postgres >= 9.5 和 SQLite >= 3.24.0 支援 |
回傳
Promise<Array<Model, boolean|null>> | 回傳一個包含兩個元素的陣列,第一個元素是新的記錄,第二個元素是 |
公開方法
public changed(key: string, value: any): boolean | Array source
如果以字串呼叫 changed,則會傳回布林值,指出 dataValues
中該鍵的值是否與 _previousDataValues
中的值不同。
如果呼叫 changed 時沒有帶任何引數,則會回傳一個已變更的鍵的陣列。
如果呼叫 changed 時沒有帶任何引數,而且沒有任何鍵已變更,則會回傳 false
。
請注意,當手動編輯巢狀屬性(例如 JSON)的屬性時,此函式會回傳 false
,在這些情況下,您必須手動呼叫 changed('key', true)
。寫入全新的物件(例如深度複製)將會被偵測到。
參數
名稱 | 類型 | 屬性 | 描述 |
key | string |
|
要檢查或變更狀態的鍵 |
value | 任何 |
|
要設定的值 |
範例
```
const mdl = await MyModel.findOne();
mdl.myJsonField.a = 1;
console.log(mdl.changed()) => false
mdl.save(); // this will not save anything
mdl.changed('myJsonField', true);
console.log(mdl.changed()) => ['myJsonField']
mdl.save(); // will save
```
public async decrement(fields: string | Array | object, options: object): Promise source
遞減一個或多個欄位的值。這是直接在資料庫中完成的,這表示它不會使用目前儲存在實例上的值。遞減是使用
SET column = column - X
查詢完成。更新後的實例預設會在 Postgres 中回傳。但是,在其他方言中,您需要重新載入才能取得新值。
參數
名稱 | 類型 | 屬性 | 描述 |
fields | string | Array | object | 如果提供字串,則該欄位會遞減 options 中給定的 |
|
options | object |
|
遞減選項 |
options.by | number |
|
要遞減的數字 |
options.silent | boolean |
|
如果為 true,則不會更新 updatedAt 時間戳記。 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
options.returning | boolean |
|
附加 RETURNING * 以取回自動產生值(僅限 Postgres) |
範例
instance.decrement('number') // decrement number by 1
instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
// decrement answer by 42, and tries by 1.
// `by` is ignored, since each column has its own value
instance.decrement({ answer: 42, tries: 1}, { by: 2 })
請參閱
public async destroy(options: object): Promise source
銷毀對應於此實例的列。根據您對 paranoid 的設定,該列將被完全刪除,或將其 deletedAt 時間戳記設定為目前時間。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
刪除選項 |
options.force | boolean |
|
如果設定為 true,則 paranoid 模型實際上會被刪除 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
public get(key: string, options: object): object | any source
如果未給定任何鍵,則傳回實例的所有值,也會叫用虛擬 getter。
如果提供了 key,且該 key 存在欄位或虛擬 getter,則會呼叫該 getter - 否則會回傳 key 的值。
public getDataValue(key: string): any source
取得基礎資料值的值
參數
名稱 | 類型 | 屬性 | 描述 |
key | string | 要在實例資料儲存中查找的 key |
回傳
任何 |
public async increment(fields: string | Array | object, options: object): Promise<Model> since 4.0.0 source
遞增一個或多個欄位的值。這是於資料庫中完成,表示它不使用目前儲存在實例上的值。遞增是使用一個
SET column = column + X
查詢完成。更新後的實例預設會在 Postgres 中回傳。但是,在其他方言中,您需要重新載入才能取得新值。
參數
名稱 | 類型 | 屬性 | 描述 |
fields | string | Array | object | 如果提供字串,則該欄會依 options 中給定的 |
|
options | object |
|
options |
options.by | number |
|
要遞增的數字 |
options.silent | boolean |
|
如果為 true,則不會更新 updatedAt 時間戳記。 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
options.returning | boolean |
|
附加 RETURNING * 以取回自動產生值(僅限 Postgres) |
範例
instance.increment('number') // increment number by 1
instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
// increment answer by 42, and tries by 1.
// `by` is ignored, since each column has its own value
instance.increment({ answer: 42, tries: 1}, { by: 2 })
請參閱
public isSoftDeleted(): boolean source
輔助方法,用於判斷實例是否為「軟刪除」。如果實作者將 deletedAt
屬性重新命名為其他名稱,則此方法特別有用。此方法需要啟用 paranoid
。
public previous(key: string): any | Array<any> source
從 _previousDataValues
傳回鍵的先前值。
如果沒有 key 呼叫,則會回傳所有已變更的值的先前值
參數
名稱 | 類型 | 屬性 | 描述 |
key | string |
|
要取得先前值的 key |
public async reload(options: object): Promise<Model> source
就地重新整理目前的實例,亦即,使用來自資料庫的目前資料更新物件,並回傳相同的物件。這與執行 find(Instance.id)
不同,因為後者會建立並回傳新的實例。使用此方法,對實例的所有參考都會使用新的資料更新,而且不會建立新的物件。
public async restore(options: object): Promise source
還原對應此實例的資料列。僅適用於偏執模型。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
還原選項 |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
public async save(options: object): Promise<Model> source
驗證此實例,如果驗證通過,則將其持久化至資料庫。
回傳一個 Promise,該 Promise 會解析為已儲存的實例(或拒絕並拋出 Sequelize.ValidationError
,該錯誤會為每個驗證失敗的欄位提供一個屬性,並包含該欄位的錯誤訊息)。
此方法經過最佳化,僅對已變更的欄位執行 UPDATE。如果沒有任何變更,則不會執行 SQL 查詢。
此方法無法識別預先載入的關聯。換句話說,如果某些其他模型實例 (子項) 是與此實例 (父項) 一起預先載入,而且您變更了子項中的某些內容,則呼叫 save()
只會忽略子項發生的變更。
參數
名稱 | 類型 | 屬性 | 描述 |
options | object |
|
儲存選項 |
options.fields | string[] |
|
表示資料庫欄位的可選字串陣列。如果提供欄位,則只會驗證和儲存這些欄位。 |
options.silent | boolean |
|
如果為 true,則不會更新 updatedAt 時間戳記。 |
options.validate | boolean |
|
如果為 false,則不會執行驗證。 |
options.hooks | boolean |
|
執行建立/更新前和更新後的驗證 Hook |
options.logging | Function |
|
在執行查詢以記錄 sql 時執行的函數。 |
options.transaction | Transaction |
|
在下執行查詢的事務 |
options.searchPath | string |
|
指定 schema search_path 的可選參數(僅限 Postgres) |
options.returning | boolean |
|
附加 RETURNING * 以取回自動產生值(僅限 Postgres) |
public set(key: string | object, value: any, options: object): Model source
Set 用於更新實例上的值(即實例的 sequelize 表示法,請記住,在您實際呼叫 save
之前,不會持續保存任何內容)。在其最基本的形式中,set
會更新儲存在基礎 dataValues
物件中的值。但是,如果為 key 定義了自訂 setter 函數,則會改為呼叫該函數。若要略過 setter,您可以在 options 物件中傳遞 raw: true
。
如果使用物件呼叫 set,它會循環執行該物件,並針對每個 key、value 配對遞迴呼叫 set。如果您將 raw 設定為 true,則基礎 dataValues 會直接設定為傳遞的物件,或者如果 dataValues 已包含值,則會用於擴充 dataValues。
在呼叫 set 時,會儲存欄位的先前值,並設定已變更的旗標(請參閱 changed
)。
如果擁有這些關聯的值,則 Set 也可用於建置關聯的實例。當將 set 與關聯搭配使用時,您需要確保屬性 key 與關聯的別名相符,同時也要確保已設定正確的 include 選項 (來自 .build() 或 .findOne())
如果使用 JSON/JSONB 屬性上的點分隔 key 呼叫,它會設定巢狀的值,並將整個物件標示為已變更。
請參閱
- 有關包含的詳細資訊,請參閱 Model.findAll
public setDataValue(key: string, value: any) source
更新基礎資料值
參數
名稱 | 類型 | 屬性 | 描述 |
key | string | 要在實例資料儲存中設定的 key |
|
value | 任何 | 給定 key 的新值 |
public toJSON(): object source
將實例轉換為 JSON 表示法。代理到以沒有 key 的情況下呼叫 get
。這表示取得從資料庫取得的所有值,並套用所有自訂 getter。
請參閱
public async update(values: object, options: object): Promise<Model> source
這與呼叫 set
然後呼叫 save
相同,但它只會儲存傳遞給它的確切值,使其更具原子性且更安全。