UNPKG

sequelize

Version:

Multi dialect ORM for Node.JS/io.js

566 lines (534 loc) 60.5 kB
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../"> <title data-ice="title">Tutorial</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> <link data-ice="userStyle" rel="stylesheet" href="user/css/0-style.css"> </head> <body class="layout-container manual-root" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <a data-ice="repoURL" href="https://github.com/sequelize/sequelize.git" class="repo-url-github">Repository</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> </header> <nav class="navigation" data-ice="nav"><div class="manual-toc-root"> <div data-ice="manual" data-toc-name="installation"> <ul class="manual-toc"> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-installation" data-section-count="&#x25A0;&#x25A0;" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html" data-ice="link">Getting started</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#installation" data-ice="link">Installation</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#setting-up-a-connection" data-ice="link">Setting up a connection</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#test-the-connection" data-ice="link">Test the connection</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#your-first-model" data-ice="link">Your first model</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#your-first-query" data-ice="link">Your first query</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#application-wide-model-options" data-ice="link">Application wide model options</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a href="manual/installation/getting-started.html#promises" data-ice="link">Promises</a></li> </ul> </div> <div data-ice="manual" data-toc-name="tutorial"> <ul class="manual-toc"> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html" data-ice="link">Model definition</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#data-types" data-ice="link">Data types</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#range-types" data-ice="link">Range types</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#special-cases" data-ice="link">Special Cases</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#deferrable" data-ice="link">Deferrable</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#getters-setters" data-ice="link">Getters &amp; setters</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#defining-as-part-of-a-property" data-ice="link">Defining as part of a property</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#defining-as-part-of-the-model-options" data-ice="link">Defining as part of the model options</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#helper-functions-for-use-inside-getter-and-setter-definitions" data-ice="link">Helper functions for use inside getter and setter definitions</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#validations" data-ice="link">Validations</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#validators-and-allownull-" data-ice="link">Validators and allowNull</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#model-validations" data-ice="link">Model validations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#configuration" data-ice="link">Configuration</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#import" data-ice="link">Import</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#optimistic-locking" data-ice="link">Optimistic Locking</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#database-synchronization" data-ice="link">Database synchronization</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#expansion-of-models" data-ice="link">Expansion of models</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a href="manual/tutorial/models-definition.html#indexes" data-ice="link">Indexes</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html" data-ice="link">Model usage</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#data-retrieval-finders" data-ice="link">Data retrieval / Finders</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#find-search-for-one-specific-element-in-the-database" data-ice="link">find - Search for one specific element in the database</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#findorcreate-search-for-a-specific-element-or-create-it-if-not-available" data-ice="link">findOrCreate - Search for a specific element or create it if not available</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#findandcountall-search-for-multiple-elements-in-the-database-returns-both-data-and-total-count" data-ice="link">findAndCountAll - Search for multiple elements in the database, returns both data and total count</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#findall-search-for-multiple-elements-in-the-database" data-ice="link">findAll - Search for multiple elements in the database</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#complex-filtering-or-not-queries" data-ice="link">Complex filtering / OR / NOT queries</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#manipulating-the-dataset-with-limit-offset-order-and-group" data-ice="link">Manipulating the dataset with limit, offset, order and group</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#raw-queries" data-ice="link">Raw queries</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#count-count-the-occurrences-of-elements-in-the-database" data-ice="link">count - Count the occurrences of elements in the database</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#max-get-the-greatest-value-of-a-specific-attribute-within-a-specific-table" data-ice="link">max - Get the greatest value of a specific attribute within a specific table</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#min-get-the-least-value-of-a-specific-attribute-within-a-specific-table" data-ice="link">min - Get the least value of a specific attribute within a specific table</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#sum-sum-the-value-of-specific-attributes" data-ice="link">sum - Sum the value of specific attributes</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#eager-loading" data-ice="link">Eager loading</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#including-everything" data-ice="link">Including everything</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#including-soft-deleted-records" data-ice="link">Including soft deleted records</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#ordering-eager-loaded-associations" data-ice="link">Ordering Eager Loaded Associations</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a href="manual/tutorial/models-usage.html#nested-eager-loading" data-ice="link">Nested eager loading</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html" data-ice="link">Querying</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#attributes" data-ice="link">Attributes</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#where" data-ice="link">Where</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#basics" data-ice="link">Basics</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#operators" data-ice="link">Operators</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#range-operators" data-ice="link">Range Operators</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#combinations" data-ice="link">Combinations</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#jsonb" data-ice="link">JSONB</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#nested-object" data-ice="link">Nested object</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#nested-key" data-ice="link">Nested key</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#containment" data-ice="link">Containment</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#relations-associations" data-ice="link">Relations / Associations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#pagination-limiting" data-ice="link">Pagination / Limiting</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a href="manual/tutorial/querying.html#ordering" data-ice="link">Ordering</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html" data-ice="link">Instances</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#building-a-non-persistent-instance" data-ice="link">Building a non-persistent instance</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#creating-persistent-instances" data-ice="link">Creating persistent instances</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#updating-saving-persisting-an-instance" data-ice="link">Updating / Saving / Persisting an instance</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#destroying-deleting-persistent-instances" data-ice="link">Destroying / Deleting persistent instances</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#working-in-bulk-creating-updating-and-destroying-multiple-rows-at-once-" data-ice="link">Working in bulk (creating, updating and destroying multiple rows at once)</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#values-of-an-instance" data-ice="link">Values of an instance</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#reloading-instances" data-ice="link">Reloading instances</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#incrementing-certain-values-of-an-instance" data-ice="link">Incrementing certain values of an instance</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a href="manual/tutorial/instances.html#decrementing-certain-values-of-an-instance" data-ice="link">Decrementing certain values of an instance</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html" data-ice="link">Associations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#one-to-one-associations" data-ice="link">One-To-One associations</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#belongsto" data-ice="link">BelongsTo</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#foreign-keys" data-ice="link">Foreign keys</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#target-keys" data-ice="link">Target keys</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#hasone" data-ice="link">HasOne</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#difference-between-hasone-and-belongsto" data-ice="link">Difference between HasOne and BelongsTo</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#one-to-many-associations" data-ice="link">One-To-Many associations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#belongs-to-many-associations" data-ice="link">Belongs-To-Many associations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#scopes" data-ice="link">Scopes</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#1-m" data-ice="link">1:m</a></li> <li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#n-m" data-ice="link">n:m</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#naming-strategy" data-ice="link">Naming strategy</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#associating-objects" data-ice="link">Associating objects</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#check-associations" data-ice="link">Check associations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#foreign-keys" data-ice="link">Foreign Keys</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#enforcing-a-foreign-key-reference-without-constraints" data-ice="link">Enforcing a foreign key reference without constraints</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#creating-with-associations" data-ice="link">Creating with associations</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#creating-elements-of-a-belongsto-has-many-or-hasone-association" data-ice="link">Creating elements of a &quot;BelongsTo&quot;, &quot;Has Many&quot; or &quot;HasOne&quot; association</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#creating-elements-of-a-belongsto-association-with-an-alias" data-ice="link">Creating elements of a &quot;BelongsTo&quot; association with an alias</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a href="manual/tutorial/associations.html#creating-elements-of-a-hasmany-or-belongstomany-association" data-ice="link">Creating elements of a &quot;HasMany&quot; or &quot;BelongsToMany&quot; association</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html" data-ice="link">Transactions</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#managed-transaction-auto-callback-" data-ice="link">Managed transaction (auto-callback)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#throw-errors-to-rollback" data-ice="link">Throw errors to rollback</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#automatically-pass-transactions-to-all-queries" data-ice="link">Automatically pass transactions to all queries</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#concurrent-partial-transactions" data-ice="link">Concurrent/Partial transactions</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#without-cls-enabled" data-ice="link">Without CLS enabled</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#isolation-levels" data-ice="link">Isolation levels</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#unmanaged-transaction-then-callback-" data-ice="link">Unmanaged transaction (then-callback)</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#options" data-ice="link">Options</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a href="manual/tutorial/transactions.html#usage-with-other-sequelize-methods" data-ice="link">Usage with other sequelize methods</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;" data-link="manual/tutorial/scopes.html"><a href="manual/tutorial/scopes.html" data-ice="link">Scopes</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a href="manual/tutorial/scopes.html#definition" data-ice="link">Definition</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a href="manual/tutorial/scopes.html#usage" data-ice="link">Usage</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a href="manual/tutorial/scopes.html#merging" data-ice="link">Merging</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a href="manual/tutorial/scopes.html#associations" data-ice="link">Associations</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html" data-ice="link">Hooks</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#order-of-operations" data-ice="link">Order of Operations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#declaring-hooks" data-ice="link">Declaring Hooks</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#removing-hooks" data-ice="link">Removing hooks</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#global-universal-hooks" data-ice="link">Global / universal hooks</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#sequelize-options-define-default-hook-" data-ice="link">Sequelize.options.define (default hook)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#sequelize-addhook-permanent-hook-" data-ice="link">Sequelize.addHook (permanent hook)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#instance-hooks" data-ice="link">Instance hooks</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#model-hooks" data-ice="link">Model hooks</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#associations" data-ice="link">Associations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#a-note-about-transactions" data-ice="link">A Note About Transactions</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a href="manual/tutorial/hooks.html#internal-transactions" data-ice="link">Internal Transactions</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;" data-link="manual/tutorial/raw-queries.html"><a href="manual/tutorial/raw-queries.html" data-ice="link">Raw queries</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/raw-queries.html"><a href="manual/tutorial/raw-queries.html#replacements" data-ice="link">Replacements</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/raw-queries.html"><a href="manual/tutorial/raw-queries.html#bind-parameter" data-ice="link">Bind Parameter</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="&#x25A0;&#x25A0;&#x25A0;&#x25A0;" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html" data-ice="link">Migrations</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#the-cli" data-ice="link">The CLI</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#skeleton" data-ice="link">Skeleton</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#functions" data-ice="link">Functions</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#createtable-tablename-attributes-options-" data-ice="link">createTable(tableName, attributes, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#droptable-tablename-options-" data-ice="link">dropTable(tableName, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#dropalltables-options-" data-ice="link">dropAllTables(options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#renametable-before-after-options-" data-ice="link">renameTable(before, after, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#showalltables-options-" data-ice="link">showAllTables(options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#describetable-tablename-options-" data-ice="link">describeTable(tableName, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#addcolumn-tablenameoroptions-attributename-datatypeoroptions-options-" data-ice="link">addColumn(tableNameOrOptions, attributeName, dataTypeOrOptions, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#removecolumn-tablenameoroptions-attributename-options-" data-ice="link">removeColumn(tableNameOrOptions, attributeName, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#changecolumn-tablename-attributename-datatypeoroptions-options-" data-ice="link">changeColumn(tableName, attributeName, dataTypeOrOptions, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#renamecolumn-tablename-attrnamebefore-attrnameafter-options-" data-ice="link">renameColumn(tableName, attrNameBefore, attrNameAfter, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#addindex-tablename-attributes-options-" data-ice="link">addIndex(tableName, attributes, options)</a></li> <li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#removeindex-tablename-indexnameorattributes-options-" data-ice="link">removeIndex(tableName, indexNameOrAttributes, options)</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a href="manual/tutorial/migrations.html#programmatic-use" data-ice="link">Programmatic use</a></li> </ul> </div> <div data-ice="manual" data-toc-name="advanced"> <ul class="manual-toc"> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-advanced" data-section-count="&#x25A0;&#x25A0;" data-link="manual/advanced/legacy.html"><a href="manual/advanced/legacy.html" data-ice="link">Working with legacy tables</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a href="manual/advanced/legacy.html#tables" data-ice="link">Tables</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a href="manual/advanced/legacy.html#fields" data-ice="link">Fields</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a href="manual/advanced/legacy.html#primary-keys" data-ice="link">Primary keys</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a href="manual/advanced/legacy.html#foreign-keys" data-ice="link">Foreign keys</a></li> </ul> </div> <div data-ice="manual" data-toc-name="reference"> <ul class="manual-toc"> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-reference" data-section-count="&#x25A0;&#x25A0;&#x25A0;&#x25A0;&#x25A0;" data-link="identifiers.html"><a href="identifiers.html" data-ice="link">Reference</a></li> <li data-ice="manualNav" class="indent-h2" data-link="identifiers.html"><a href="identifiers.html#class" data-ice="link">Class</a></li> <li data-ice="manualNav" class="indent-h2" data-link="identifiers.html"><a href="identifiers.html#variable" data-ice="link">Variable</a></li> </ul> </div> <div data-ice="manual" data-toc-name="faq"> <ul class="manual-toc"> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-faq" data-section-count="&#x25A0;" data-link="manual/faq/whos-using.html"><a href="manual/faq/whos-using.html" data-ice="link">Who&apos;s using sequelize?</a></li> <li data-ice="manualNav" class="indent-h1 manual-color manual-color-faq" data-section-count="&#x25A0;" data-link="manual/faq/imprint.html"><a href="manual/faq/imprint.html" data-ice="link">Imprint</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/faq/imprint.html"><a href="manual/faq/imprint.html#author-s-" data-ice="link">AUTHOR(S)</a></li> <li data-ice="manualNav" class="indent-h2" data-link="manual/faq/imprint.html"><a href="manual/faq/imprint.html#inhaltliche-verantwortung" data-ice="link">INHALTLICHE VERANTWORTUNG</a></li> </ul> </div> </div> </nav> <div class="content" data-ice="content"><div class="github-markdown"> <div class="manual-breadcrumb-list"> <a href="./manual/./index.html">Manual</a> <span>&#xBB;</span> <span data-ice="title">Tutorial</span> </div> <div data-ice="content"><h1 id="model-usage">Model usage</h1> <h2 id="data-retrieval-finders">Data retrieval / Finders</h2> <p>Finder methods are intended to query data from the database. They do <em>not</em> return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for <a href="http://docs.sequelizejs.com/en/latest/docs/instances/"><em>instances</em></a>.</p> <p>In this document we&apos;ll explore what finder methods can do:</p> <h3 id="find-search-for-one-specific-element-in-the-database">find - Search for one specific element in the database</h3> <pre><code class="lang-js"><code class="source-code prettyprint">// search for known ids Project.findById(123).then(function(project) { // project will be an instance of Project and stores the content of the table entry // with id 123. if such an entry is not defined you will get null }) // search for attributes Project.findOne({ where: {title: &apos;aProject&apos;} }).then(function(project) { // project will be the first entry of the Projects table with the title &apos;aProject&apos; || null }) Project.findOne({ where: {title: &apos;aProject&apos;}, attributes: [&apos;id&apos;, [&apos;name&apos;, &apos;title&apos;]] }).then(function(project) { // project will be the first entry of the Projects table with the title &apos;aProject&apos; || null // project.title will contain the name of the project })</code> </code></pre> <h3 id="findorcreate-search-for-a-specific-element-or-create-it-if-not-available">findOrCreate - Search for a specific element or create it if not available</h3> <p>The method <code>findOrCreate</code> can be used to check if a certain element already exists in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created.</p> <p>Let&apos;s assume we have an empty database with a <code>User</code> model which has a <code>username</code> and a <code>job</code>.</p> <pre><code class="lang-js"><code class="source-code prettyprint">User .findOrCreate({where: {username: &apos;sdepold&apos;}, defaults: {job: &apos;Technical Lead JavaScript&apos;}}) .spread(function(user, created) { console.log(user.get({ plain: true })) console.log(created) /* { username: &apos;sdepold&apos;, job: &apos;Technical Lead JavaScript&apos;, id: 1, createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET), updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET) } created: true */ })</code> </code></pre> <p>The code created a new instance. So when we already have an instance ...</p> <pre><code class="lang-js"><code class="source-code prettyprint">User .create({ username: &apos;fnord&apos;, job: &apos;omnomnom&apos; }) .then(function() { User .findOrCreate({where: {username: &apos;fnord&apos;}, defaults: {job: &apos;something else&apos;}}) .spread(function(user, created) { console.log(user.get({ plain: true })) console.log(created) /* { username: &apos;fnord&apos;, job: &apos;omnomnom&apos;, id: 2, createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET), updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET) } created: false */ }) })</code> </code></pre> <p>... the existing entry will not be changed. See the <code>job</code> of the second user, and the fact that created was false.</p> <h3 id="findandcountall-search-for-multiple-elements-in-the-database-returns-both-data-and-total-count">findAndCountAll - Search for multiple elements in the database, returns both data and total count</h3> <p>This is a convenience method that combines<code>findAll</code> and <code>count</code> (see below) this is useful when dealing with queries related to pagination where you want to retrieve data with a <code>limit</code> and <code>offset</code> but also need to know the total number of records that match the query:</p> <p>The success handler will always receive an object with two properties:</p> <ul> <li><code>count</code> - an integer, total number records matching the where clause</li> <li><code>rows</code> - an array of objects, the records matching the where clause, within the limit and offset range<pre><code class="lang-js"><code class="source-code prettyprint">Project .findAndCountAll({ where: { title: { $like: &apos;foo%&apos; } }, offset: 10, limit: 2 }) .then(function(result) { console.log(result.count); console.log(result.rows); });</code> </code></pre> </li> </ul> <p><code>findAndCountAll</code> also supports includes. Only the includes that are marked as <code>required</code> will be added to the count part:</p> <p>Suppose you want to find all users who have a profile attached:</p> <pre><code class="lang-js"><code class="source-code prettyprint">User.findAndCountAll({ include: [ { model: Profile, required: true} ], limit: 3 });</code> </code></pre> <p>Because the include for <code>Profile</code> has <code>required</code> set it will result in an inner join, and only the users who have a profile will be counted. If we remove <code>required</code> from the include, both users with and without profiles will be counted. Adding a <code>where</code> clause to the include automatically makes it required:</p> <pre><code class="lang-js"><code class="source-code prettyprint">User.findAndCountAll({ include: [ { model: Profile, where: { active: true }} ], limit: 3 });</code> </code></pre> <p>The query above will only count users who have an active profile, because <code>required</code> is implicitly set to true when you add a where clause to the include.</p> <p>The options object that you pass to <code>findAndCountAll</code> is the same as for <code>findAll</code> (described below).</p> <h3 id="findall-search-for-multiple-elements-in-the-database">findAll - Search for multiple elements in the database</h3> <pre><code class="lang-js"><code class="source-code prettyprint">// find multiple entries Project.findAll().then(function(projects) { // projects will be an array of all Project instances }) // also possible: Project.all().then(function(projects) { // projects will be an array of all Project instances }) // search for specific attributes - hash usage Project.findAll({ where: { name: &apos;A Project&apos; } }).then(function(projects) { // projects will be an array of Project instances with the specified name }) // search with string replacements Project.findAll({ where: [&quot;id &gt; ?&quot;, 25] }).then(function(projects) { // projects will be an array of Projects having a greater id than 25 }) // search within a specific range Project.findAll({ where: { id: [1,2,3] } }).then(function(projects) { // projects will be an array of Projects having the id 1, 2 or 3 // this is actually doing an IN query }) Project.findAll({ where: { id: { $and: {a: 5} // AND (a = 5) $or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6) $gt: 6, // id &gt; 6 $gte: 6, // id &gt;= 6 $lt: 10, // id &lt; 10 $lte: 10, // id &lt;= 10 $ne: 20, // id != 20 $between: [6, 10], // BETWEEN 6 AND 10 $notBetween: [11, 15], // NOT BETWEEN 11 AND 15 $in: [1, 2], // IN [1, 2] $notIn: [1, 2], // NOT IN [1, 2] $like: &apos;%hat&apos;, // LIKE &apos;%hat&apos; $notLike: &apos;%hat&apos; // NOT LIKE &apos;%hat&apos; $iLike: &apos;%hat&apos; // ILIKE &apos;%hat&apos; (case insensitive) (PG only) $notILike: &apos;%hat&apos; // NOT ILIKE &apos;%hat&apos; (PG only) $overlap: [1, 2] // &amp;&amp; [1, 2] (PG array overlap operator) $contains: [1, 2] // @&gt; [1, 2] (PG array contains operator) $contained: [1, 2] // &lt;@ [1, 2] (PG array contained by operator) $any: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only) }, status: { $not: false, // status NOT FALSE } } })</code> </code></pre> <h3 id="complex-filtering-or-not-queries">Complex filtering / OR / NOT queries</h3> <p>It&apos;s possible to do complex where queries with multiple levels of nested AND, OR and NOT conditions. In order to do that you can use <code>$or</code>, <code>$and</code> or <code>$not</code>:</p> <pre><code class="lang-js"><code class="source-code prettyprint">Project.findOne({ where: { name: &apos;a project&apos;, $or: [ { id: [1,2,3] }, { id: { $gt: 10 } } ] } }) Project.findOne({ where: { name: &apos;a project&apos;, id: { $or: [ [1,2,3], { $gt: 10 } ] } } })</code> </code></pre> <p>Both pieces of code will generate the following:</p> <pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM `Projects` WHERE ( `Projects`.`name` = &apos;a project&apos; AND (`Projects`.`id` IN (1,2,3) OR `Projects`.`id` &gt; 10) ) LIMIT 1;</code> </code></pre> <p><code>$not</code> example:</p> <pre><code class="lang-js"><code class="source-code prettyprint">Project.findOne({ where: { name: &apos;a project&apos;, $not: [ { id: [1,2,3] }, { array: { $contains: [3,4,5] } } ] } });</code> </code></pre> <p>Will generate:</p> <pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM `Projects` WHERE ( `Projects`.`name` = &apos;a project&apos; AND NOT (`Projects`.`id` IN (1,2,3) OR `Projects`.`array` @&gt; ARRAY[1,2,3]::INTEGER[]) ) LIMIT 1;</code> </code></pre> <h3 id="manipulating-the-dataset-with-limit-offset-order-and-group">Manipulating the dataset with limit, offset, order and group</h3> <p>To get more relevant data, you can use limit, offset, order and grouping:</p> <pre><code class="lang-js"><code class="source-code prettyprint">// limit the results of the query Project.findAll({ limit: 10 }) // step over the first 10 elements Project.findAll({ offset: 10 }) // step over the first 10 elements, and take 2 Project.findAll({ offset: 10, limit: 2 })</code> </code></pre> <p>The syntax for grouping and ordering are equal, so below it is only explained with a single example for group, and the rest for order. Everything you see below can also be done for group</p> <pre><code class="lang-js"><code class="source-code prettyprint">Project.findAll({order: &apos;title DESC&apos;}) // yields ORDER BY title DESC Project.findAll({group: &apos;name&apos;}) // yields GROUP BY name</code> </code></pre> <p>Notice how in the two examples above, the string provided is inserted verbatim into the query, i.e. column names are not escaped. When you provide a string to order/group, this will always be the case. If you want to escape column names, you should provide an array of arguments, even though you only want to order/group by a single column</p> <pre><code class="lang-js"><code class="source-code prettyprint">something.findOne({ order: [ &apos;name&apos;, // will return `name` &apos;username DESC&apos;, // will return `username DESC` -- i.e. don&apos;t do it! [&apos;username&apos;, &apos;DESC&apos;], // will return `username` DESC sequelize.fn(&apos;max&apos;, sequelize.col(&apos;age&apos;)), // will return max(`age`) [sequelize.fn(&apos;max&apos;, sequelize.col(&apos;age&apos;)), &apos;DESC&apos;], // will return max(`age`) DESC [sequelize.fn(&apos;otherfunction&apos;, sequelize.col(&apos;col1&apos;), 12, &apos;lalala&apos;), &apos;DESC&apos;], // will return otherfunction(`col1`, 12, &apos;lalala&apos;) DESC [sequelize.fn(&apos;otherfunction&apos;, sequelize.fn(&apos;awesomefunction&apos;, sequelize.col(&apos;col&apos;))), &apos;DESC&apos;] // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite! [{ raw: &apos;otherfunction(awesomefunction(`col`))&apos; }, &apos;DESC&apos;] // This won&apos;t be quoted, but direction will be added ] })</code> </code></pre> <p>To recap, the elements of the order/group array can be the following:</p> <ul> <li>String - will be quoted</li> <li>Array - first element will be quoted, second will be appended verbatim</li> <li>Object -<ul> <li>Raw will be added verbatim without quoting</li> <li>Everything else is ignored, and if raw is not set, the query will fail</li> </ul> </li> <li>Sequelize.fn and Sequelize.col returns functions and quoted cools</li> </ul> <h3 id="raw-queries">Raw queries</h3> <p>Sometimes you might be expecting a massive dataset that you just want to display, without manipulation. For each row you select, Sequelize creates an instance with functions for update, delete, get associations etc. If you have thousands of rows, this might take some time. If you only need the raw data and don&apos;t want to update anything, you can do like this to get the raw data.</p> <pre><code class="lang-js"><code class="source-code prettyprint">// Are you expecting a massive dataset from the DB, // and don&apos;t want to spend the time building DAOs for each entry? // You can pass an extra query option to get the raw data instead: Project.findAll({ where: { ... }, raw: true })</code> </code></pre> <h3 id="count-count-the-occurrences-of-elements-in-the-database">count - Count the occurrences of elements in the database</h3> <p>There is also a method for counting database objects:</p> <pre><code class="lang-js"><code class="source-code prettyprint">Project.count().then(function(c) { console.log(&quot;There are &quot; + c + &quot; projects!&quot;) }) Project.count({ where: [&quot;id &gt; ?&quot;, 25] }).then(function(c) { console.log(&quot;There are &quot; + c + &quot; projects with an id greater than 25.&quot;) })</code> </code></pre> <h3 id="max-get-the-greatest-value-of-a-specific-attribute-within-a-specific-table">max - Get the greatest value of a specific attribute within a specific table</h3> <p>And here is a method for getting the max value of an attribute:f</p> <pre><code class="lang-js"><code class="source-code prettyprint">/* Let&apos;s assume 3 person objects with an attribute age. The first one is 10 years old, the second one is 5 years old, the third one is 40 years old. */ Project.max(&apos;age&apos;).then(function(max) { // this will return 40 }) Project.max(&apos;age&apos;, { where: { age: { lt: 20 } } }).then(function(max) { // will be 10 })</code> </code></pre> <h3 id="min-get-the-least-value-of-a-specific-attribute-within-a-specific-table">min - Get the least value of a specific attribute within a specific table</h3> <p>And here is a method for getting the min value of an attribute:</p> <pre><code class="lang-js"><code class="source-code prettyprint">/* Let&apos;s assume 3 person objects with an attribute age. The first one is 10 years old, the second one is 5 years old, the third one is 40 years old. */ Project.min(&apos;age&apos;).then(function(min) { // this will return 5 }) Project.min(&apos;age&apos;, { where: { age: { $gt: 5 } } }).then(function(min) { // will be 10 })</code> </code></pre> <h3 id="sum-sum-the-value-of-specific-attributes">sum - Sum the value of specific attributes</h3> <p>In order to calculate the sum over a specific column of a table, you can use the <code>sum</code> method.</p> <pre><code class="lang-js"><code class="source-code prettyprint">/* Let&apos;s assume 3 person objects with an attribute age. The first one is 10 years old, the second one is 5 years old, the third one is 40 years old. */ Project.sum(&apos;age&apos;).then(function(sum) { // this will return 55 }) Project.sum(&apos;age&apos;, { where: { age: { $gt: 5 } } }).then(function(sum) { // will be 50 })</code> </code></pre> <h2 id="eager-loading">Eager loading</h2> <p>When you are retrieving data from the database there is a fair chance that you also want to get associations with the same query - this is called eager loading. The basic idea behind that, is the use of the attribute <code>include</code> when you are calling <code>find</code> or <code>findAll</code>. Lets assume the following setup:</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = sequelize.define(&apos;user&apos;, { name: Sequelize.STRING }) , Task = sequelize.define(&apos;task&apos;, { name: Sequelize.STRING }) , Tool = sequelize.define(&apos;tool&apos;, { name: Sequelize.STRING }) Task.belongsTo(User) User.hasMany(Task) User.h