UNPKG

sequelize

Version:

Multi dialect ORM for Node.JS/io.js

445 lines (407 loc) 71.9 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="associations">Associations</h1> <p>This section describes the various association types in sequelize. When calling a method such as <code>User.hasOne(Project)</code>, we say that the <code>User</code> model (the model that the function is being invoked on) is the <strong>source</strong> and the <code>Project</code> model (the model being passed as an argument) is the <strong>target</strong>.</p> <h2 id="one-to-one-associations">One-To-One associations</h2> <p>One-To-One associations are associations between exactly two models connected by a single foreign key.</p> <h3 id="belongsto">BelongsTo</h3> <p>BelongsTo associations are associations where the foreign key for the one-to-one relation exists on the <strong>source model</strong>.</p> <p>A simple example would be a <strong>Player</strong> being part of a <strong>Team</strong> with the foreign key on the player.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var Player = this.sequelize.define(&apos;player&apos;, {/* attributes */}) , Team = this.sequelize.define(&apos;team&apos;, {/* attributes */}); Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team</code> </code></pre> <h4 id="foreign-keys">Foreign keys</h4> <p>By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name.</p> <p>The default casing is <code>camelCase</code> however if the source model is configured with <code>underscored: true</code> the foreignKey will be <code>snake_case</code>.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = this.sequelize.define(&apos;user&apos;, {/* attributes */}) , Company = this.sequelize.define(&apos;company&apos;, {/* attributes */}); User.belongsTo(Company); // Will add companyId to user var User = this.sequelize.define(&apos;user&apos;, {/* attributes */}, {underscored: true}) , Company = this.sequelize.define(&apos;company&apos;, { uuid: { type: Sequelize.UUID, primaryKey: true } }); User.belongsTo(Company); // Will add company_uuid to user</code> </code></pre> <p>In cases where <code>as</code> has been defined it will be used in place of the target model name.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = this.sequelize.define(&apos;user&apos;, {/* attributes */}) , UserRole = this.sequelize.define(&apos;userRole&apos;, {/* attributes */}); User.belongsTo(UserRole, {as: &apos;role&apos;}); // Adds roleId to user rather than userRoleId</code> </code></pre> <p>In all cases the default foreign key can be overwritten with the <code>foreignKey</code> option. When the foreign key option is used, Sequelize will use it as-is:</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = this.sequelize.define(&apos;user&apos;, {/* attributes */}) , Company = this.sequelize.define(&apos;company&apos;, {/* attributes */}); User.belongsTo(Company, {foreignKey: &apos;fk_company&apos;}); // Adds fk_company to User</code> </code></pre> <h4 id="target-keys">Target keys</h4> <p>The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model&apos;s primary key. To define a custom column, use the <code>targetKey</code> option.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = this.sequelize.define(&apos;user&apos;, {/* attributes */}) , Company = this.sequelize.define(&apos;company&apos;, {/* attributes */}); User.belongsTo(Company, {foreignKey: &apos;fk_companyname&apos;, targetKey: &apos;name&apos;}); // Adds fk_companyname to User</code> </code></pre> <h3 id="hasone">HasOne</h3> <p>HasOne associations are associations where the foreign key for the one-to-one relation exists on the <strong>target model</strong>.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = sequelize.define(&apos;user&apos;, {/* ... */}) var Project = sequelize.define(&apos;project&apos;, {/* ... */}) // One-way associations Project.hasOne(User) /* In this example hasOne will add an attribute projectId to the User model! Furthermore, Project.prototype will gain the methods getUser and setUser according to the first parameter passed to define. If you have underscore style enabled, the added attribute will be project_id instead of projectId. The foreign key will be placed on the users table. You can also define the foreign key, e.g. if you already have an existing database and want to work on it: */ Project.hasOne(User, { foreignKey: &apos;initiator_id&apos; }) /* Because Sequelize will use the model&apos;s name (first parameter of define) for the accessor methods, it is also possible to pass a special option to hasOne: */ Project.hasOne(User, { as: &apos;Initiator&apos; }) // Now you will get Project#getInitiator and Project#setInitiator // Or let&apos;s define some self references var Person = sequelize.define(&apos;person&apos;, { /* ... */}) Person.hasOne(Person, {as: &apos;Father&apos;}) // this will add the attribute FatherId to Person // also possible: Person.hasOne(Person, {as: &apos;Father&apos;, foreignKey: &apos;DadId&apos;}) // this will add the attribute DadId to Person // In both cases you will be able to do: Person#setFather Person#getFather // If you need to join a table twice you can double join the same table Team.hasOne(Game, {as: &apos;HomeTeam&apos;, foreignKey : &apos;homeTeamId&apos;}); Team.hasOne(Game, {as: &apos;AwayTeam&apos;, foreignKey : &apos;awayTeamId&apos;}); Game.belongsTo(Team);</code> </code></pre> <p>Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.</p> <h3 id="difference-between-hasone-and-belongsto">Difference between HasOne and BelongsTo</h3> <p>In Sequelize 1:1 relationship can be set using HasOne and BelongsTo. They are suitable for different scenarios. Lets study this difference using an example.</p> <p>Suppose we have two tables to link <strong>Player</strong> and <strong>Team</strong>. Lets define their models.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var Player = this.sequelize.define(&apos;player&apos;, {/* attributes */}) , Team = this.sequelize.define(&apos;team&apos;, {/* attributes */});</code> </code></pre> <p>When we link two models in Sequelize we can refer them as pairs of <strong>source</strong> and <strong>target</strong> models. Like this</p> <p>Having <strong>Player</strong> as the <strong>source</strong> and <strong>Team</strong> as the <strong>target</strong></p> <pre><code class="lang-js"><code class="source-code prettyprint">Player.belongsTo(Team); //Or Player.hasOne(Team);</code> </code></pre> <p>Having <strong>Team</strong> as the <strong>source</strong> and <strong>Player</strong> as the <strong>target</strong></p> <pre><code class="lang-js"><code class="source-code prettyprint">Team.belongsTo(Player); //Or Team.hasOne(Player);</code> </code></pre> <p>HasOne and BelongsTo insert the association key in different models from each other. HasOne inserts the association key in <strong>target</strong> model whereas BelongsTo inserts the association key in the <strong>source</strong> model.</p> <p>Here is an example demonstrating use cases of BelongsTo and HasOne.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var Player = this.sequelize.define(&apos;player&apos;, {/* attributes */}) , Coach = this.sequelize.define(&apos;coach&apos;, {/* attributes */}) , Team = this.sequelize.define(&apos;team&apos;, {/* attributes */});</code> </code></pre> <p>Suppose our <code>Player</code> model has information about its team as <code>teamId</code> column. Information about each Team&apos;s <code>Coach</code> is stored in the <code>Team</code> model as <code>coachId</code> column. These both scenarios requires different kind of 1:1 relation because foreign key relation is present on different models each time.</p> <p>When information about association is present in <strong>source</strong> model we can use <code>belongsTo</code>. In this case <code>Player</code> is suitable for <code>belongsTo</code> because it has <code>teamId</code> column.</p> <pre><code class="lang-js"><code class="source-code prettyprint">Player.belongsTo(Team) // `teamId` will be added on Player / Source model</code> </code></pre> <p>When information about association is present in <strong>target</strong> model we can use <code>hasOne</code>. In this case <code>Coach</code> is suitable for <code>hasOne</code> because <code>Team</code> model store information about its <code>Coach</code> as <code>coachId</code> field.</p> <pre><code class="lang-js"><code class="source-code prettyprint">Coach.hasOne(Team) // `coachId` will be added on Team / Target model</code> </code></pre> <h2 id="one-to-many-associations">One-To-Many associations</h2> <p>One-To-Many associations are connecting one source with multiple targets. The targets however are again connected to exactly one specific source.</p> <pre><code class="lang-js"><code class="source-code prettyprint">var User = sequelize.define(&apos;user&apos;, {/* ... */}) var Project = sequelize.define(&apos;project&apos;, {/* ... */}) // OK. Now things get more complicated (not really visible to the user :)). // First let&apos;s define a hasMany association Project.hasMany(User, {as: &apos;Workers&apos;})</code> </code></pre> <p>This will add the attribute <code>projectId</code> or <code>project_id</code> to User. Instances of Project will get the accessors <code>getWorkers</code> and <code>setWorkers</code>. We could just leave it the way it is and let it be a one-way association. But we want more! Let&apos;s define it the other way around by creating a many to many association in the next section:</p> <p>Sometimes you may need to associate records on different columns, you may use <code>sourceKey</code> option:</p> <pre><code class="lang-js"><code class="source-code prettyprint">var City = sequelize.define(&apos;city&apos;, { countryCode: Sequelize.STRING }); var Country = sequelize.define(&apos;country&apos;, { isoCode: Sequelize.STRING }); // Here we can connect countries and cities base on country code Country.hasMany(City, {foreignKey: &apos;countryCode&apos;, sourceKey: &apos;isoCode&apos;}); City.belongsTo(Country, {foreignKey: &apos;countryCode&apos;, targetKey: &apos;isoCode&apos;});</code> </code></pre> <h2 id="belongs-to-many-associations">Belongs-To-Many associations</h2> <p>Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.</p> <pre><code class="lang-js"><code class="source-code prettyprint">Project.belongsToMany(User, {through: &apos;UserProject&apos;}); User.belongsToMany(Project, {through: &apos;UserProject&apos;});</code> </code></pre> <p>This will create a new model called UserProject with the equivalent foreign keys <code>projectId</code> and <code>userId</code>. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).</p> <p>Defining <code>through</code> is <strong>required</strong>. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.</p> <p>This will add methods <code>getUsers</code>, <code>setUsers</code>, <code>addUser</code>,<code>addUsers</code> to <code>Project</code>, and <code>getProjects</code>, <code>setProjects</code>, <code>addProject</code>, and <code>addProjects</code> to <code>User</code>.</p> <p>Sometimes you may want to rename your models when using them in associations. Let&apos;s define users as workers and projects as tasks by using the alias (<code>as</code>) option. We will also manually define the foreign keys to use:</p> <pre><code class="lang-js"><code class="source-code prettyprint">User.belongsToMany(Project, { as: &apos;Tasks&apos;, through: &apos;worker_tasks&apos;, foreignKey: &apos;userId&apos; }) Project.belongsToMany(User, { as: &apos;Workers&apos;, through: &apos;worker_tasks&apos;, foreignKey: &apos;projectId&apos; })</code> </code></pre> <p><code>foreignKey</code> will allow you to set <strong>source model</strong> key in the <strong>through</strong> relation. <code>otherKey</code> will allow you to set <strong>target model</strong> key in the <strong>through</strong> relation.</p> <pre><code class="lang-js"><code class="source-code prettyprint">User.belongsToMany(Project, { as: &apos;Tasks&apos;, through: &apos;worker_tasks&apos;, foreignKey: &apos;userId&apos;, otherKey: &apos;projectId&apos;})</code> </code></pre> <p>Of course you can also define self references with belongsToMany:</p> <pre><code class="lang-js"><code class="source-code prettyprint">Person.belongsToMany(Person, { as: &apos;Children&apos;, through: &apos;PersonChildren&apos; }) // This will create the table PersonChildren which stores the ids of the objects.</code> </code></pre> <p>If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:</p> <pre><code class="lang-js"><code class="source-code prettyprint">User = sequelize.define(&apos;user&apos;, {}) Project = sequelize.define(&apos;project&apos;, {}) UserProjects = sequelize.define(&apos;userProjects&apos;, { status: DataTypes.STRING }) User.belongsToMany(Project, { through: UserProjects }) Project.belongsToMany(User, { through: UserProjects })</code> </code></pre> <p>To add a new project to a user and set its status, you pass extra <code>options.through</code> to the setter, which contains the attributes for the join table</p> <pre><code class="lang-js"><code class="source-code prettyprint">user.addProject(project, { through: { status: &apos;started&apos; }})</code> </code></pre> <p>By default the code above will add projectId and userId to the UserProjects table, and <em>remove any previously defined primary key attribute</em> - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns. To enforce a primary key on the <code>UserProjects</code> model you can add it manually.</p> <pre><code class="lang-js"><code class="source-code prettyprint">UserProjects = sequelize.define(&apos;userProjects&apos;, { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, status: DataTypes.STRING })</code> </code></pre> <p>With Belongs-To-Many you can query based on <strong>through</strong> relation and select specific attributes. For example using <code>findAll</code> with <strong>through</strong></p> <pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ model: Project, through: { attributes: [&apos;createdAt&apos;, &apos;startedAt&apos;, &apos;finishedAt&apos;], where: {completed: true} } }] });</code> </code></pre> <h2 id="scopes">Scopes</h2> <p>This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see <a href="./manual/scopes">Scopes</a>.</p> <p>Association scopes allow you to place a scope (a set of default attributes for <code>get</code> and <code>create</code>) on the association. Scopes can be placed both on the associated model (the target of the association), and on the through table for n:m relations.</p> <h4 id="1-m">1:m</h4> <p>Assume we have tables Comment, Post, and Image. A comment can be associated to either an image or a post via <code>commentable_id</code> and <code>commentable</code> - we say that Post and Image are <code>Commentable</code></p> <pre><code class="lang-js"><code class="source-code prettyprint">this.Comment = this.sequelize.define(&apos;comment&apos;, { title: Sequelize.STRING, commentable: Sequelize.STRING, commentable_id: Sequelize.INTEGER }); this.Comment.prototype.getItem = function() { return this[&apos;get&apos; + this.get(&apos;commentable&apos;).substr(0, 1).toUpperCase() + this.get(&apos;commentable&apos;).substr(1)](); }; this.Post.hasMany(this.Comment, { foreignKey: &apos;commentable_id&apos;, constraints: false, scope: { commentable: &apos;post&apos; } }); this.Comment.belongsTo(this.Post, { foreignKey: &apos;commentable_id&apos;, constrai