1<!DOCTYPE html><html><head> 2 <meta charset="utf-8"> 3 <base data-ice="baseUrl" href="/v4/./"> 4 <title data-ice="title">Manual | Sequelize | The node.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</title> 5 <link type="text/css" rel="stylesheet" href="/v4/css/style.css"> 6 <link type="text/css" rel="stylesheet" href="/v4/css/prettify-tomorrow.css"> 7
7<script src="/v4/script/prettify/prettify.js"></script>
7 8 9 10
10<script src="/v4/script/manual.js"></script>
vendor: 1 bytes, line 10
10
11<script data-ice="userScript" src="/v4/user/script/0-script.js"></script>
11 12<link data-ice="userStyle" rel="stylesheet" href="/v4/user/css/0-style.css"> 13<link data-ice="userStyle" rel="stylesheet" href="/v4/user/css/1-theme.css"> 14<link rel="shortcut icon" type="image/x-icon" href="/v4/favicon.ico"><meta name="robots" content="noindex"></head> 15<body class="layout-container manual-root manual-index" data-ice="rootContainer"> 16 17<header><a href="/v4/"><img src="/v4/manual/asset/logo-small.png" class="header-logo"></a> 18 <a href="/v4/./">Home</a> 19 20 <a href='/v4/identifiers'>Reference</a> 21 <a href='/v4/source'>Source</a> 22 23 <a data-ice="repoURL" href="https://github.com/sequelize/sequelize.git" class="repo-url-github">Repository</a><a href="https://sequelize.org/slack" class="slack-link"><img class="slack-logo" src="/v4/manual/asset/slack.svg">Join us on Slack</a> 24 <div class="search-box"> 25 <span> 26 <img src="/v4/./image/search.png"> 27 <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> 28 </span> 29 <ul class="search-result"></ul> 30 </div> 31</header> 32 33<nav class="navigation" data-ice="nav"><div class="manual-toc-root"> 34 35<div data-ice="manual" data-toc-name="installation"> 36 <ul class="manual-toc"> 37 38 <li data-ice="manualNav" class="indent-h1 manual-color manual-color-installation" data-section-count="â â " data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started'>Getting started</a></li> 39<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#installation'>Installation</a></li> 40<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#setting-up-a-connection'>Setting up a connection</a></li> 41<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#test-the-connection'>Test the connection</a></li> 42<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#your-first-model'>Your first model</a></li> 43<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#your-first-query'>Your first query</a></li> 44<li data-ice="manualNav" class="indent-h3" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#application-wide-model-options'>Application wide model options</a></li> 45<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/getting-started.html"><a data-ice='link' href='/v4/manual/installation/getting-started#promises'>Promises</a></li> 46<li data-ice="manualNav" class="indent-h1 manual-color manual-color-installation" data-section-count="â â " data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage'>Basic usage</a></li> 47<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#options'>Options</a></li> 48<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#read-replication'>Read replication</a></li> 49<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#dialects'>Dialects</a></li> 50<li data-ice="manualNav" class="indent-h3" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#mysql'>MySQL</a></li> 51<li data-ice="manualNav" class="indent-h3" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#sqlite'>SQLite</a></li> 52<li data-ice="manualNav" class="indent-h3" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#postgresql'>PostgreSQL</a></li> 53<li data-ice="manualNav" class="indent-h3" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#mssql'>MSSQL</a></li> 54<li data-ice="manualNav" class="indent-h2" data-link="manual/installation/usage.html"><a data-ice='link' href='/v4/manual/installation/usage#executing-raw-sql-queries'>Executing raw SQL queries</a></li> 55</ul> 56 </div> 57<div data-ice="manual" data-toc-name="tutorial"> 58 <ul class="manual-toc"> 59 60 <li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â â " data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition'>Model definition</a></li> 61<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#timestamps'>Timestamps</a></li> 62<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#data-types'>Data types</a></li> 63<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#array-enum-'>Array(ENUM)</a></li> 64<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#range-types'>Range types</a></li> 65<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#deferrable'>Deferrable</a></li> 66<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#getters-setters'>Getters & setters</a></li> 67<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#defining-as-part-of-a-property'>Defining as part of a property</a></li> 68<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#defining-as-part-of-the-model-options'>
68Defining as part of the model options</a></li> 69<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#helper-functions-for-use-inside-getter-and-setter-definitions'>Helper functions for use inside getter and setter definitions</a></li> 70<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#validations'>Validations</a></li> 71<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#validators-and-allownull-'>Validators and allowNull</a></li> 72<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#model-validations'>Model validations</a></li> 73<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#configuration'>Configuration</a></li> 74<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#import'>Import</a></li> 75<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#optimistic-locking'>Optimistic Locking</a></li> 76<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#database-synchronization'>Database synchronization</a></li> 77<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#expansion-of-models'>Expansion of models</a></li> 78<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-definition.html"><a data-ice='link' href='/v4/manual/tutorial/models-definition#indexes'>Indexes</a></li> 79<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â â " data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage'>Model usage</a></li> 80<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#data-retrieval-finders'>Data retrieval / Finders</a></li> 81<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-find-search-for-one-specific-element-in-the-database'>find - Search for one specific element in the database</a></li> 82<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-findorcreate-search-for-a-specific-element-or-create-it-if-not-available'>findOrCreate - Search for a specific element or create it if not available</a></li> 83<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-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</a></li> 84<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-findall-search-for-multiple-elements-in-the-database'>findAll - Search for multiple elements in the database</a></li> 85<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#complex-filtering-or-not-queries'>Complex filtering / OR / NOT queries</a></li> 86<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#manipulating-the-dataset-with-limit-offset-order-and-group'>Manipulating the dataset with limit, offset, order and group</a></li> 87<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#raw-queries'>Raw queries</a></li> 88<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-count-count-the-occurrences-of-elements-in-the-database'>count - Count the occurrences of elements in the database</a></li> 89<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-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</a></li> 90<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-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</a></li> 91<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#-sum-sum-the-value-of-specific-attributes'>sum - Sum the value of specific attributes</a></li> 92<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#eager-loading'>Eager loading</a></li> 93<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#top-level-where-with-eagerly-loaded-models'>Top level where with eagerly loaded models</a></li> 94<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#including-everything'>Including everything</a></li> 95<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#including-soft-deleted-records'>Including soft deleted records</a></li> 96<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#ordering-eager-loaded-associations'>Ordering Eager Loaded Associations</a></li> 97<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/models-usage.html"><a data-ice='link' href='/v4/manual/tutorial/models-usage#nested-eager-loading'>Nested eager loading</a></li> 98<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â â â " data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying'>Querying</a></li> 99<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#attributes'>Attributes</a></li> 100<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#where'>Where</a></li> 101<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#basics'>Basics</a></li> 102<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#operators'>Operators</a></li> 103<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#range-operators'>Range Operators</a></li> 104<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#combinations'>Combinations</a></li> 105<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#operators-aliases'>Operators Aliases</a></li> 106<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#operators-security'>Operators security</a></li> 107<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#json'>JSON</a></li> 108<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#postgresql'>PostgreSQL</a></li> 109<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#mssql'>MSSQL</a></li> 110<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#jsonb'>JSONB</a></li> 111<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#nested-object'>Nested object</a></li> 112<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#nested-key'>Nested key</a></li> 113<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#containment'>Containment</a></li> 114<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#relations-associations'>Relations / Associations</a></li> 115<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#pagination-limiting'>Pagination / Limiting</a></li> 116<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#ordering'>Ordering</a></li> 117<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/querying.html"><a data-ice='link' href='/v4/manual/tutorial/querying#table-hint'>Table Hint</a></li> 118<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â " data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances'>Instances</a></li> 119<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#building-a-non-persistent-instance'>Building a non-persistent instance</a></li> 120<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#creating-persistent-instances'>Creating persistent instances</a></li> 121<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#updating-saving-persisting-an-instance'>Updating / Saving / Persisting an instance</a></li> 122<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#destroying-deleting-persistent-instances'>Destroying / Deleting persistent instances</a></li> 123<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#working-in-bulk-creating-updating-and-destroying-multiple-rows-at-once-'>Working in bulk (creating, updating and destroying multiple rows at once)</a></li> 124<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#values-of-an-instance'>Values of an instance</a></li> 125<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#reloading-instances'>Reloading instances</a></li> 126<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#incrementing'>Incrementing</a></li> 127<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/instances.html"><a data-ice='link' href='/v4/manual/tutorial/instances#decrementing'>Decrementing</a></li> 128<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â â â " data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations'>Associations</a></li> 129<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#one-to-one-associations'>One-To-One associations</a></li> 130<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#belongsto'>BelongsTo</a></li> 131<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#foreign-keys'>
131Foreign keys</a></li> 132<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#target-keys'>Target keys</a></li> 133<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#hasone'>HasOne</a></li> 134<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#difference-between-hasone-and-belongsto'>Difference between HasOne and BelongsTo</a></li> 135<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#one-to-many-associations-hasmany-'>One-To-Many associations (hasMany)</a></li> 136<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#belongs-to-many-associations'>Belongs-To-Many associations</a></li> 137<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#scopes'>Scopes</a></li> 138<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#1-m'>1:m</a></li> 139<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#n-m'>n:m</a></li> 140<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#naming-strategy'>Naming strategy</a></li> 141<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#associating-objects'>Associating objects</a></li> 142<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#check-associations'>Check associations</a></li> 143<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#foreign-keys'>
143Foreign Keys</a></li> 144<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#enforcing-a-foreign-key-reference-without-constraints'>Enforcing a foreign key reference without constraints</a></li> 145<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#creating-with-associations'>Creating with associations</a></li> 146<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#creating-elements-of-a-belongsto-has-many-or-hasone-association'>Creating elements of a "BelongsTo", "Has Many" or "HasOne" association</a></li> 147<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#creating-elements-of-a-belongsto-association-with-an-alias'>Creating elements of a "BelongsTo" association with an alias</a></li> 148<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/associations.html"><a data-ice='link' href='/v4/manual/tutorial/associations#creating-elements-of-a-hasmany-or-belongstomany-association'>Creating elements of a "HasMany" or "BelongsToMany" association</a></li> 149<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â " data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions'>Transactions</a></li> 150<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#managed-transaction-auto-callback-'>Managed transaction (auto-callback)</a></li> 151<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#throw-errors-to-rollback'>Throw errors to rollback</a></li> 152<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#automatically-pass-transactions-to-all-queries'>Automatically pass transactions to all queries</a></li> 153<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#concurrent-partial-transactions'>Concurrent/Partial transactions</a></li> 154<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#without-cls-enabled'>Without CLS enabled</a></li> 155<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#isolation-levels'>Isolation levels</a></li> 156<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#unmanaged-transaction-then-callback-'>Unmanaged transaction (then-callback)</a></li> 157<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#options'>Options</a></li> 158<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#usage-with-other-sequelize-methods'>Usage with other sequelize methods</a></li> 159<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/transactions.html"><a data-ice='link' href='/v4/manual/tutorial/transactions#after-commit-hook'>After commit hook</a></li> 160<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â " data-link="manual/tutorial/scopes.html"><a data-ice='link' href='/v4/manual/tutorial/scopes'>Scopes</a></li> 161<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a data-ice='link' href='/v4/manual/tutorial/scopes#definition'>Definition</a></li> 162<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a data-ice='link' href='/v4/manual/tutorial/scopes#usage'>Usage</a></li> 163<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a data-ice='link' href='/v4/manual/tutorial/scopes#merging'>Merging</a></li> 164<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/scopes.html"><a data-ice='link' href='/v4/manual/tutorial/scopes#associations'>Associations</a></li> 165<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â " data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks'>Hooks</a></li> 166<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#order-of-operations'>Order of Operations</a></li> 167<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#declaring-hooks'>Declaring Hooks</a></li> 168<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html">
168<a data-ice='link' href='/v4/manual/tutorial/hooks#removing-hooks'>Removing hooks</a></li> 169<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#global-universal-hooks'>Global / universal hooks</a></li> 170<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#sequelize-options-define-default-hook-'>Sequelize.options.define (default hook)</a></li> 171<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#sequelize-addhook-permanent-hook-'>Sequelize.addHook (permanent hook)</a></li> 172<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#instance-hooks'>Instance hooks</a></li> 173<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#model-hooks'>Model hooks</a></li> 174<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#associations'>Associations</a></li> 175<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#a-note-about-transactions'>A Note About Transactions</a></li> 176<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/hooks.html"><a data-ice='link' href='/v4/manual/tutorial/hooks#internal-transactions'>Internal Transactions</a></li> 177<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â " data-link="manual/tutorial/raw-queries.html"><a data-ice='link' href='/v4/manual/tutorial/raw-queries'>Raw queries</a></li> 178<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/raw-queries.html"><a data-ice='link' href='/v4/manual/tutorial/raw-queries#replacements'>Replacements</a></li> 179<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/raw-queries.html"><a data-ice='link' href='/v4/manual/tutorial/raw-queries#bind-parameter'>Bind Parameter</a></li> 180<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â â â " data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations'>Migrations</a></li> 181<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#the-cli'>The CLI</a></li> 182<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#installing-cli'>Installing CLI</a></li> 183<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#bootstrapping'>Bootstrapping</a></li> 184<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#configuration'>Configuration</a></li> 185<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#creating-first-model-and-migration-'>Creating first Model (and Migration)</a></li> 186<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#running-migrations'>Running Migrations</a></li> 187<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#undoing-migrations'>Undoing Migrations</a></li> 188<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#creating-first-seed'>Creating First Seed</a></li> 189<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#running-seeds'>Running Seeds</a></li> 190<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#undoing-seeds'>Undoing Seeds</a></li> 191<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#advance-topics'>Advance Topics</a></li> 192<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#migration-skeleton'>Migration Skeleton</a></li> 193<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#the-sequelizerc-file'>
193The .sequelizerc File</a></li> 194<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#dynamic-configuration'>Dynamic Configuration</a></li> 195<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#using-environment-variables'>Using Environment Variables</a></li> 196<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#specifying-dialect-options'>Specifying Dialect Options</a></li> 197<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#production-usages'>Production Usages</a></li> 198<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#storage'>Storage</a></li> 199<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#migration-storage'>Migration Storage</a></li> 200<li data-ice="manualNav" class="indent-h4" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#seed-storage'>Seed Storage</a></li> 201<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#configuration-connection-string'>Configuration Connection String</a></li> 202<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#connecting-over-ssl'>Connecting over SSL</a></li> 203<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#programmatic-use'>Programmatic use</a></li> 204<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/migrations.html"><a data-ice='link' href='/v4/manual/tutorial/migrations#query-interface'>Query Interface</a></li> 205<li data-ice="manualNav" class="indent-h1 manual-color manual-color-tutorial" data-section-count="â â â " data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4'>Upgrade to V4</a></li> 206<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#changelog'>Changelog</a></li> 207<li data-ice="manualNav" class="indent-h2" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#breaking-changes'>Breaking Changes</a></li> 208<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#node'>Node</a></li> 209<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#general'>General</a></li> 210<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#config-options'>Config / Options</a></li> 211<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#data-types'>Data Types</a></li> 212<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#transactions-cls'>Transactions / CLS</a></li> 213<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#raw-queries'>Raw Queries</a></li> 214<li data-ice="manualNav" class="indent-h3" data-link="manual/tutorial/upgrade-to-v4.html"><a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4#others'>Others</a></li> 215</ul> 216 </div> 217<div data-ice="manual" data-toc-name="advanced"> 218 <ul class="manual-toc"> 219 220 <li data-ice="manualNav" class="indent-h1 manual-color manual-color-advanced" data-section-count="â â " data-link="manual/advanced/legacy.html"><a data-ice='link' href='/v4/manual/advanced/legacy'>Working with legacy tables</a></li> 221<li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a data-ice='link' href='/v4/manual/advanced/legacy#tables'>Tables</a></li> 222<li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a data-ice='link' href='/v4/manual/advanced/legacy#fields'>Fields</a></li> 223<li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a data-ice='link' href='/v4/manual/advanced/legacy#primary-keys'>Primary keys</a></li> 224<li data-ice="manualNav" class="indent-h2" data-link="manual/advanced/legacy.html"><a data-ice='link' href='/v4/manual/advanced/legacy#foreign-keys'>
224Foreign keys</a></li> 225</ul> 226 </div> 227<div data-ice="manual" data-toc-name="reference"> 228 <ul class="manual-toc"> 229 230 <li data-ice="manualNav" class="indent-h1 manual-color manual-color-reference" data-section-count="â â â â â " data-link="identifiers.html"><a data-ice='link' href='/v4/identifiers'>Reference</a></li> 231<li data-ice="manualNav" class="indent-h2" data-link="identifiers.html"><a data-ice='link' href='/v4/identifiers#class'>Class</a></li> 232<li data-ice="manualNav" class="indent-h2" data-link="identifiers.html"><a data-ice='link' href='/v4/identifiers#function'>Function</a></li> 233<li data-ice="manualNav" class="indent-h2" data-link="identifiers.html"><a data-ice='link' href='/v4/identifiers#variable'>Variable</a></li> 234</ul> 235 </div> 236<div data-ice="manual" data-toc-name="faq"> 237 <ul class="manual-toc"> 238 239 <li data-ice="manualNav" class="indent-h1 manual-color manual-color-faq" data-section-count="â " data-link="manual/faq/whos-using.html"><a data-ice='link' href='/v4/manual/faq/whos-using'>Who's using sequelize?</a></li> 240<li data-ice="manualNav" class="indent-h1 manual-color manual-color-faq" data-section-count="â " data-link="manual/faq/imprint.html"><a data-ice='link' href='/v4/manual/faq/imprint'>Imprint</a></li> 241<li data-ice="manualNav" class="indent-h2" data-link="manual/faq/imprint.html"><a data-ice='link' href='/v4/manual/faq/imprint#author-s-'>AUTHOR(S)</a></li> 242<li data-ice="manualNav" class="indent-h2" data-link="manual/faq/imprint.html"><a data-ice='link' href='/v4/manual/faq/imprint#inhaltliche-verantwortung'>INHALTLICHE VERANTWORTUNG</a></li> 243</ul> 244 </div> 245</div> 246</nav> 247 248<div class="content" data-ice="content"><div class="github-markdown"> 249 <div class="manual-user-index" data-ice="manualUserIndex"><p></p><div> 250 <div class="center logo"> 251 <img src="/v4/manual/asset/logo-small.png" alt="logo"> 252 </div> 253 <div class="center sequelize">Sequelize 254</div> 255 256</div><p></p> 257<p><a href="https://travis-ci.org/sequelize/sequelize"><img src="https://img.shields.io/travis/sequelize/sequelize/master.svg?style=flat-square" alt="Travis build"></a> 258<a href="https://npmjs.org/package/sequelize"><img src="https://img.shields.io/npm/dm/sequelize.svg?style=flat-square" alt="npm"></a> 259<a href="https://github.com/sequelize/sequelize/releases"><img src="https://img.shields.io/npm/v/sequelize.svg?style=flat-square" alt="npm"></a></p> 260<p>Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.</p> 261<h2 id="example-usage">Example usage</h2> 262<pre><code class="lang-js"><code class="source-code prettyprint">const Sequelize = require('sequelize'); 263const sequelize = new Sequelize('database', 'username', 'password', { 264 host: 'localhost', 265 dialect: 'mysql'|'sqlite'|'postgres'|'mssql', 266 267 pool: { 268 max: 5, 269 min: 0, 270 acquire: 30000, 271 idle: 10000 272 }, 273 274 // SQLite only 275 storage: 'path/to/database.sqlite', 276 277 // http://docs.sequelizejs.com/manual/tutorial/querying.html#operators 278 operatorsAliases: false 279}); 280 281const User = sequelize.define('user', { 282 username: Sequelize.STRING, 283 birthday: Sequelize.DATE 284}); 285 286sequelize.sync() 287 .then(() => User.create({ 288 username: 'janedoe', 289 birthday: new Date(1980, 6, 20) 290 })) 291 .then(jane => { 292 console.log(jane.toJSON()); 293 });</code> 294</code></pre> 295<p>Please use <a href="/v4/manual/installation/getting-started">Getting Started</a> to learn more. If you wish to learn about Sequelize API please use <a href="/v4/identifiers">API Reference</a></p> 296</div> 297 298 <p class="manual-badge" data-ice="manualBadge"><img src="/v4/./manual-badge.svg"></p> 299 300 <div class="manual-cards"> 301 302 <div class="manual-card-wrap" data-ice="cards"> 303 <h1 data-ice="label" class="manual-color manual-color-installation" data-section-count="â â "><span data-ice="label-inner">Getting started</span></h1> 304 <div class="manual-card"> 305 <div data-ice="card"><h1>Getting started</h1><h2>Installation</h2><p>Sequelize is available via NPM and Yarn.</p><pre><code class="lang-bash"><code class="source-code prettyprint">// Using NPM 306$ npm install --save sequelize 307 308# And one of the following: 309$ npm install --save pg pg-hstore 310$ npm install --save mysql2 311$ npm install --save sqlite3 312$ npm install --save tedious // MSSQL 313 314// Using Yarn 315$ yarn add sequelize 316 317# And one of the following: 318$ yarn add pg pg-hstore 319$ yarn add mysql2 320$ yarn add sqlite3 321$ yarn add tedious // MSSQL</code> 322</code></pre><h2>Setting up a connection</h2><p>Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database if you're connecting to the DB from a single process. If you're connecting to the DB from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of "max connection pool size divided by number of instances". So, if you wanted a max connection pool size of 90 and you had 3 worker processes, each process's instance should have a max connection pool size of 30.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Sequelize = require('sequelize'); 323const sequelize = new Sequelize('database', 'username', 'password', { 324 host: 'localhost', 325 dialect: 'mysql'|'sqlite'|'postgres'|'mssql', 326 operatorsAliases: false, 327 328 pool: { 329 max: 5, 330 min: 0, 331 acquire: 30000, 332 idle: 10000 333 }, 334 335 // SQLite only 336 storage: 'path/to/database.sqlite' 337}); 338 339// Or you can simply use a connection uri 340const sequelize = new Sequelize('postgres://user:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="156574666655706d74786579703b767a78">[email protected]</a>:5432/dbname');</code> 341</code></pre><p>The Sequelize constructor takes a whole slew of options that are available via the <a href='/v4/class/lib/sequelize.js~sequelize'>API reference</a>.</p><h2>Test the connection</h2><p>You can use the <code>.authenticate()</code> function like this to test the connection.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize 342 .authenticate() 343 .then(() => { 344 console.log('Connection has been established successfully.'); 345 }) 346 .catch(err => { 347 console.error('Unable to connect to the database:', err); 348 });</code> 349</code></pre><h2>Your first model</h2><p>Models are defined with <code>sequelize.define('name', {attributes}, {options})</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = sequelize.define('user', { 350 firstName: { 351 type: Sequelize.STRING 352 }, 353 lastName: { 354 type: Sequelize.STRING 355 } 356}); 357 358// force: true will drop the table if it already exists 359User.sync({force: true}).then(() => { 360 // Table created 361 return User.create({ 362 firstName: 'John', 363 lastName: 'Hancock' 364 }); 365});</code> 366</code></pre><p>You can read more about creating models at <a href='/v4/class/lib/model.js~model'>Model API reference</a></p><h2>Your first query</h2><pre><code class="lang-js"><code class="source-code prettyprint">
366User.findAll().then(users => { 367 console.log(users) 368})</code> 369</code></pre><p>You can read more about finder functions on models like <code>.findAll()</code> at <a href='/v4/manual/tutorial/models-usage#data-retrieval-finders'>Data retrieval</a> or how to do specific queries like <code>WHERE</code> and <code>JSONB</code> at <a href='/v4/manual/tutorial/querying'>Querying</a>.</p><h3>Application wide model options</h3><p>The Sequelize constructor takes a <code>define</code> option which will be used as the default options for all defined models.</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('connectionUri', { 370 define: { 371 timestamps: false // true by default 372 } 373}); 374 375const User = sequelize.define('user', {}); // timestamps is false by default 376const Post = sequelize.define('post', {}, { 377 timestamps: true // timestamps will now be true 378});</code> 379</code></pre><h2>Promises</h2><p>Sequelize uses <a href="http://bluebirdjs.com">Bluebird</a> promises to control async control-flow.</p><p><strong>Note:</strong> <em>Sequelize use independent copy of Bluebird instance. You can access it using 380 <code>Sequelize.Promise</code> if you want to set any Bluebird specific options</em></p><p>If you are unfamiliar with how promises work, don't worry, you can read up on them <a href="http://bluebirdjs.com/docs/why-promises.html">here</a>.</p><p>Basically, a promise represents a value which will be present at some point - "I promise you I will give you a result or an error at some point". This means that</p><pre><code class="lang-js"><code class="source-code prettyprint">// DON'T DO THIS 381user = User.findOne() 382 383console.log(user.get('firstName'));</code> 384</code></pre><p><em>will never work!</em> This is because <code>user</code> is a promise object, not a data row from the DB. The right way to do it is:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findOne().then(user => { 385 console.log(user.get('firstName')); 386});</code> 387</code></pre><p>When your environment or transpiler supports <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await">async/await</a> this will work but only in the body of an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a> function:</p><pre><code class="lang-js"><code class="source-code prettyprint">user = await User.findOne() 388 389console.log(user.get('firstName'));</code> 390</code></pre><p>Once you've got the hang of what promises are and how they work, use the <a href="http://bluebirdjs.com/docs/api-reference.html">bluebird API reference</a>
390 as your go-to tool. In particular, you'll probably be using <a href="http://bluebirdjs.com/docs/api/promise.all.html"><code>.all</code></a> a lot.</p></div> 391 <a data-ice='link' href='/v4/manual/installation/getting-started'></a> 392 </div> 393 </div> 394<div class="manual-card-wrap" data-ice="cards"> 395 <h1 data-ice="label" class="manual-color manual-color-installation" data-section-count="â â "><span data-ice="label-inner">Basic usage</span></h1> 396 <div class="manual-card"> 397 <div data-ice="card"><h1>Basic usage</h1><p>To get the ball rollin' you first have to create an instance of Sequelize. Use it the following way:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 398 dialect: 'mysql' 399});</code> 400</code></pre><p>This will save the passed database credentials and provide all further methods.</p><p>Furthermore you can specify a non-default host/port:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 401 dialect: 'mysql', 402 host: "my.server.tld", 403 port: 9821, 404})</code> 405</code></pre><p>If you just don't have a password:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize({ 406 database: 'db_name', 407 username: 'username', 408 password: null, 409 dialect: 'mysql' 410});</code> 411</code></pre><p>You can also use a connection string:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('mysql://user:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95e5f4e6e6d5f0edf4f8e5f9f0bbf6faf8">[email protected]</a>:9821/db_name', { 412 // Look to the next section for possible options 413})</code> 414</code></pre><h2>Options</h2><p>Besides the host and the port, Sequelize comes with a whole bunch of options. Here they are:</p><ul> 415<li>See <a href='/v4/class/lib/sequelize.js~sequelize'>Sequelize API</a></li> 416<li>See <a href='/v4/manual/tutorial/models-definition#configuration'>Model Definition</a></li> 417<li>See <a href='/v4/manual/tutorial/transactions'>Transactions</a></li> 418</ul><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 419 // the sql dialect of the database 420 // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql' 421 dialect: 'mysql', 422 423 // custom host; default: localhost 424 host: 'my.server.tld', 425 426 // custom port; default: dialect default 427 port: 12345, 428 429 // custom protocol; default: 'tcp' 430 // postgres only, useful for Heroku 431 protocol: null, 432 433 // disable logging; default: console.log 434 logging: false, 435 436 // you can also pass any dialect options to the underlying dialect library 437 // - default is empty 438 // - currently supported: 'mysql', 'postgres', 'mssql' 439 dialectOptions: { 440 socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock', 441 supportBigNumbers: true, 442 bigNumberStrings: true 443 }, 444 445 // the storage engine for sqlite 446 // - default ':memory:' 447 storage: 'path/to/database.sqlite', 448 449 // disable inserting undefined values as NULL 450 // - default: false 451 omitNull: true, 452 453 // a flag for using a native library or not. 454 // in the case of 'pg' -- set this to true will allow SSL support 455 // - default: false 456 native: true, 457 458 // Specify options, which are used when sequelize.define is called. 459 // The following example: 460 // define: { timestamps: false } 461 // is basically the same as: 462 // sequelize.define(name, attributes, { timestamps: false }) 463 // so defining the timestamps for each model will be not necessary 464 define: { 465 underscored: false 466 freezeTableName: false, 467 charset: 'utf8', 468 dialectOptions: { 469 collate: 'utf8_general_ci' 470 }, 471 timestamps: true 472 }, 473 474 // similar for sync: you can define this to always force sync for models 475 sync: { force: true }, 476 477 // pool configuration used to pool database connections 478 pool: { 479 max: 5, 480 idle: 30000, 481 acquire: 60000, 482 }, 483 484 // isolation level of each transaction 485 // defaults to dialect default 486 isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ 487})</code> 488</code></pre><p><strong>Hint:</strong> You can also define a custom function for the logging part. Just pass a function. The first parameter will be the string that is logged.</p><h2>Read replication</h2><p>Sequelize supports read replication, i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the write master, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is <strong>not</strong> handled by Sequelize, but should be set up by database backend).</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', null, null, { 489 dialect: 'mysql', 490 port: 3306 491 replication: { 492 read: [ 493 { host: '8.8.8.8', username: 'read-username', password: 'some-password' }, 494 { host: '9.9.9.9', username: 'another-username', password: null } 495 ], 496 write: { host: '1.1.1.1', username: 'write-username', password: 'any-password' } 497 }, 498 pool: { // If you want to override the options used for the read/write pool you can do so here 499 max: 20, 500 idle: 30000 501 }, 502})</code> 503</code></pre><p>
503If you have any general settings that apply to all replicas you do not need to provide them for each instance. In the code above, database name and port is propagated to all replicas. The same will happen for user and password, if you leave them out for any of the replicas. Each replica has the following options:<code>host</code>,<code>port</code>,<code>username</code>,<code>password</code>,<code>database</code>.</p><p>Sequelize uses a pool to manage connections to your replicas. Internally Sequelize will maintain two pools created using <code>pool</code> configuration.</p><p>If you want to modify these, you can pass pool as an options when instantiating Sequelize, as shown above.</p><p>Each <code>write</code> or <code>useMaster: true</code> query will use write pool. For <code>SELECT</code> read pool will be used. Read replica are switched using a basic round robin scheduling.</p><h2>Dialects</h2><p>With the release of Sequelize <code>1.6.0</code>, the library got independent from specific dialects. This means, that you'll have to add the respective connector library to your project yourself.</p><h3>MySQL</h3><p>In order to get Sequelize working nicely together with MySQL, you'll need to install<code>mysql2@^1.0.0-rc.10</code>or higher. Once that's done you can use it like this:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 504 dialect: 'mysql' 505})</code> 506</code></pre><p><strong>Note:</strong> You can pass options directly to dialect library by setting the 507<code>dialectOptions</code> parameter. See <a href="/v4/manual/installation/usage#options">Options</a> 508for examples (currently only mysql is supported).</p><h3>SQLite</h3><p>For SQLite compatibility you'll need<code>sqlite3@~3.0.0</code>. Configure Sequelize like this:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 509 // sqlite! now! 510 dialect: 'sqlite', 511 512 // the storage engine for sqlite 513 // - default ':memory:' 514 storage: 'path/to/database.sqlite' 515})</code> 516</code></pre><p>Or you can use a connection string as well with a path:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('sqlite:/home/abs/path/dbname.db') 517const sequelize = new Sequelize('sqlite:relativePath/dbname.db')</code> 518</code></pre><h3>PostgreSQL</h3><p>The library for PostgreSQL is<code>pg@^5.0.0 || ^6.0.0</code> You'll just need to define the dialect:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 519 // gimme postgres, please! 520 dialect: 'postgres' 521})</code> 522</code></pre><h3>MSSQL</h3><p>The library for MSSQL is<code>tedious@^1.7.0</code> You'll just need to define the dialect:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', { 523 dialect: 'mssql' 524})</code> 525</code></pre><h2>Executing raw SQL queries</h2><p>As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function <code>sequelize.query</code>.</p><ul> 526<li>See <a href='/v4/class/lib/sequelize.js~sequelize#instance-method-query'>Sequelize.query API</a></li> 527<li>See <a href='/v4/variable/#static-variable-QueryTypes'>Query Types</a></li> 528</ul><p>Here is how it works:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Arguments for raw queries 529sequelize.query('your query', [, options]) 530 531// Quick example 532sequelize.query("SELECT * FROM myTable").then(myTableRows => { 533 console.log(myTableRows) 534}) 535 536// If you want to return sequelize instances use the model options. 537// This allows you to easily map a query to a predefined model for sequelize e.g: 538sequelize 539 .query('SELECT * FROM projects', { model: Projects }) 540 .then(projects => { 541 // Each record will now be mapped to the project's model. 542 console.log(projects) 543 }) 544 545 546// Options is an object with the following keys: 547sequelize 548 .query('SELECT 1', { 549 // A function (or false) for logging your queries 550 // Will get called for every SQL query that gets send 551 // to the server. 552 logging: console.log, 553 554 // If plain is true, then sequelize will only return the first 555 // record of the result set. In case of false it will all records.
556 plain: false, 557 558 // Set this to true if you don't have a model definition for your query. 559 raw: false, 560 561 // The type of query you are executing. The query type affects how results are formatted before they are passed back. 562 type: Sequelize.QueryTypes.SELECT 563 }) 564 565// Note the second argument being null! 566// Even if we declared a callee here, the raw: true would 567// supersede and return a raw object. 568sequelize 569 .query('SELECT * FROM projects', { raw: true }) 570 .then(projects => { 571 console.log(projects) 572 })</code> 573</code></pre><p>Replacements in a query can be done in two different ways, either using 574named parameters (starting with <code>:</code>), or unnamed, represented by a ?</p><p>The syntax used depends on the replacements option passed to the function:</p><ul> 575<li>If an array is passed, <code>?</code> will be replaced in the order that they appear in the array</li> 576<li>If an object is passed, <code>:key</code> will be replaced with the keys from that object. 577If the object contains keys not found in the query or vice versa, an exception 578will be thrown.</li> 579</ul><pre><code class="lang-js"><code class="source-code prettyprint">sequelize 580 .query( 581 'SELECT * FROM projects WHERE status = ?', 582 { raw: true, replacements: ['active'] 583 ) 584 .then(projects => { 585 console.log(projects) 586 }) 587 588sequelize 589 .query( 590 'SELECT * FROM projects WHERE status = :status ', 591 { raw: true, replacements: { status: 'active' } } 592 ) 593 .then(projects => { 594 console.log(projects) 595 })</code> 596</code></pre><p><strong>One note:</strong> If the attribute names of the table contain dots, the resulting objects will be nested:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('select 1 as `foo.bar.baz`').then(rows => { 597 console.log(JSON.stringify(rows)) 598 599 /* 600 [{ 601 "foo": { 602 "bar": { 603 "baz": 1 604 } 605 } 606 }] 607 */ 608})</code> 609</code></pre></div> 610 <a data-ice='link' href='/v4/manual/installation/usage'></a> 611 </div> 612 </div> 613<div class="manual-card-wrap" data-ice="cards"> 614 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â â "><span data-ice="label-inner">Model definition</span></h1> 615 <div class="manual-card"> 616 <div data-ice="card"><h1>Model definition</h1><p>To define mappings between a model and a table, use the <code>define</code> method.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Project = sequelize.define('project', { 617 title: Sequelize.STRING, 618 description: Sequelize.TEXT 619}) 620 621const Task = sequelize.define('task', { 622 title: Sequelize.STRING, 623 description: Sequelize.TEXT, 624 deadline: Sequelize.DATE 625})</code> 626</code></pre><p>You can also set some options on each column:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Foo = sequelize.define('foo', { 627 // instantiating will automatically set the flag to true if not set 628 flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true }, 629 630 // default values for dates => current time 631 myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }, 632 633 // setting allowNull to false will add NOT NULL to the column, which means an error will be 634 // thrown from the DB when the query is executed if the column is null. If you want to check that a value 635 // is not null before querying the DB, look at the validations section below. 636 title: { type: Sequelize.STRING, allowNull: false }, 637 638 // Creating two objects with the same value will throw an error. The unique property can be either a 639 // boolean, or a string. If you provide the same string for multiple columns, they will form a 640 // composite unique key. 641 uniqueOne: { type: Sequelize.STRING, unique: 'compositeIndex' }, 642 uniqueTwo: { type: Sequelize.INTEGER, unique: 'compositeIndex' }, 643 644 // The unique property is simply a shorthand to create a unique constraint. 645 someUnique: { type: Sequelize.STRING, unique: true }, 646 647 // It's exactly the same as creating the index in the model's options. 648 { someUnique: { type: Sequelize.STRING } },
649 { indexes: [ { unique: true, fields: [ 'someUnique' ] } ] }, 650 651 // Go on reading for further information about primary keys 652 identifier: { type: Sequelize.STRING, primaryKey: true }, 653 654 // autoIncrement can be used to create auto_incrementing integer columns 655 incrementMe: { type: Sequelize.INTEGER, autoIncrement: true }, 656 657 // You can specify a custom field name via the 'field' attribute: 658 fieldWithUnderscores: { type: Sequelize.STRING, field: 'field_with_underscores' }, 659 660 // It is possible to create foreign keys: 661 bar_id: { 662 type: Sequelize.INTEGER, 663 664 references: { 665 // This is a reference to another model 666 model: Bar, 667 668 // This is the column name of the referenced model 669 key: 'id', 670 671 // This declares when to check the foreign key constraint. PostgreSQL only. 672 deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE 673 } 674 } 675})</code> 676</code></pre><p>The comment option can also be used on a table, see <a href='/v4/manual/tutorial/models-definition#configuration'>model configuration</a></p><h2>Timestamps</h2><p>By default, Sequelize will add the attributes <code>createdAt</code> and <code>updatedAt</code> to your model so you will be able to know when the database entry went into the db and when it was updated last.</p><p>Note that if you are using Sequelize migrations you will need to add the <code>createdAt</code> and <code>updatedAt</code> fields to your migration definition:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = { 677 up(queryInterface, Sequelize) { 678 return queryInterface.createTable('my-table', { 679 id: { 680 type: Sequelize.INTEGER, 681 primaryKey: true, 682 autoIncrement: true, 683 }, 684 685 // Timestamps 686 createdAt: Sequelize.DATE, 687 updatedAt: Sequelize.DATE, 688 }) 689 }, 690 down(queryInterface, Sequelize) { 691 return queryInterface.dropTable('my-table'); 692 }, 693}</code> 694</code></pre><p>If you do not want timestamps on your models, only want some timestamps, or you are working with an existing database where the columns are named something else, jump straight on to <a href='/v4/manual/tutorial/models-definition#configuration'>configuration </a>to see how to do that.</p><h2>Data types</h2><p>Below are some of the datatypes supported by sequelize. For a full and updated list, see <a href='/v4/variable/#static-variable-DataTypes'>DataTypes</a>.</p><pre><code class="lang-js"><code class="source-code prettyprint">Sequelize.STRING // VARCHAR(255) 695Sequelize.STRING(1234) // VARCHAR(1234) 696Sequelize.STRING.BINARY // VARCHAR BINARY 697Sequelize.TEXT // TEXT 698Sequelize.TEXT('tiny') // TINYTEXT 699 700Sequelize.INTEGER // INTEGER 701Sequelize.BIGINT // BIGINT 702Sequelize.BIGINT(11) // BIGINT(11) 703 704Sequelize.FLOAT // FLOAT 705Sequelize.FLOAT(11) // FLOAT(11) 706Sequelize.FLOAT(11, 12) // FLOAT(11,12) 707 708Sequelize.REAL // REAL PostgreSQL only. 709Sequelize.REAL(11) // REAL(11) PostgreSQL only. 710Sequelize.REAL(11, 12) // REAL(11,12) PostgreSQL only. 711 712Sequelize.DOUBLE // DOUBLE 713Sequelize.DOUBLE(11) // DOUBLE(11) 714Sequelize.DOUBLE(11, 12) // DOUBLE(11,12) 715 716Sequelize.DECIMAL // DECIMAL 717Sequelize.DECIMAL(10, 2) // DECIMAL(10,2) 718 719Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres 720Sequelize.DATE(6) // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision 721Sequelize.DATEONLY // DATE without time. 722Sequelize.BOOLEAN // TINYINT(1) 723 724Sequelize.ENUM('value 1', 'value 2') // An ENUM with allowed values 'value 1' and 'value 2' 725Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only. 726Sequelize.ARRAY(Sequelize.ENUM) // Defines an array of ENUM. PostgreSQL only. 727 728Sequelize.JSON // JSON column. PostgreSQL, SQLite and MySQL only. 729Sequelize.JSONB // JSONB column. PostgreSQL only. 730 731Sequelize.BLOB // BLOB (bytea for PostgreSQL) 732Sequelize.BLOB('tiny') // TINYBLOB (bytea for PostgreSQL. Other options are medium and long) 733 734Sequelize.UUID // UUID datatype for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (use defaultValue: Sequelize.UUIDV1 or Sequelize.UUIDV4 to make sequelize generate the ids automatically) 735 736Sequelize.CIDR // CIDR datatype for PostgreSQL 737Sequelize.INET // INET datatype for PostgreSQL 738Sequelize.MACADDR // MACADDR datatype for PostgreSQL 739 740Sequelize.RANGE(Sequelize.INTEGER) // Defines int4range range. PostgreSQL only. 741Sequelize.RANGE(Sequelize.BIGINT) // Defined int8range range. PostgreSQL only. 742Sequelize.RANGE(Sequelize.DATE) // Defines tstzrange range. PostgreSQL only. 743Sequelize.RANGE(Sequelize.DATEONLY) // Defines daterange range. PostgreSQL only. 744Sequelize.RANGE(Sequelize.DECIMAL) // Defines numrange range. PostgreSQL only. 745 746Sequelize.ARRAY(Sequelize.RANGE(Sequelize.DATE)) // Defines array of tstzrange ranges. PostgreSQL only. 747 748Sequelize.GEOMETRY // Spatial column. PostgreSQL (with PostGIS) or MySQL only. 749Sequelize.GEOMETRY('POINT') // Spatial column with geometry type. PostgreSQL (with PostGIS) or MySQL only. 750Sequelize.GEOMETRY('POINT', 4326) // Spatial column with geometry type and SRID. PostgreSQL (with PostGIS) or MySQL only.</code> 751</code></pre><p>The BLOB data type allows you to insert data both as strings and as buffers. When you do a find or findAll on a model which has a BLOB column, that data will always be returned as a buffer.</p><p>If you are working with the PostgreSQL TIMESTAMP WITHOUT TIME ZONE and you need to parse it to a different timezone, please use the pg library's own parser:</p><pre><code class="lang-js"><code class="source-code prettyprint">require('pg').types.setTypeParser(1114, stringValue => { 752 return new Date(stringValue + '+0000'); 753 // e.g., UTC offset. Use any offset that you would like. 754});</code> 755</code></pre><p>In addition to the type mentioned above, integer, bigint, float and double also support unsigned and zerofill properties, which can be combined in any order: 756Be aware that this does not apply for PostgreSQL!</p><pre><code class="lang-js"><code class="source-code prettyprint">Sequelize.INTEGER.UNSIGNED // INTEGER UNSIGNED 757Sequelize.INTEGER(11).UNSIGNED // INTEGER(11) UNSIGNED 758Sequelize.INTEGER(11).ZEROFILL // INTEGER(11) ZEROFILL 759Sequelize.INTEGER(11).ZEROFILL.UNSIGNED // INTEGER(11) UNSIGNED ZEROFILL 760Sequelize.INTEGER(11).UNSIGNED.ZEROFILL // INTEGER(11) UNSIGNED ZEROFILL</code> 761</code></pre><p><em>The examples above only show integer, but the same can be done with bigint and float</em></p><p>Usage in object notation:</p><pre><code class="lang-js"><code class="source-code prettyprint">// for enums: 762sequelize.define('model', { 763 states: { 764 type: Sequelize.ENUM, 765 values: ['active', 'pending', 'deleted'] 766 } 767})</code> 768</code></pre><h3>Array(ENUM)</h3><p>Its only supported with PostgreSQL.</p><p>Array(Enum) type require special treatment. Whenever Sequelize will talk to database it has to typecast Array values with ENUM name.</p><p>So this enum name must follow this pattern <code>enum_<table_name>_<col_name></code>. If you are using <code>sync</code> then correct name will automatically be generated.</p><h3>Range types</h3><p>Since range types have extra information for their bound inclusion/exclusion it's not 769very straightforward to just use a tuple to represent them in javascript.</p><p>When supplying ranges as values you can choose from the following APIs:</p><pre><code class="lang-js"><code class="source-code prettyprint">// defaults to '["2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")' 770// inclusive lower bound, exclusive upper bound 771Timeline.create({ range: [new Date(Date.UTC(2016, 0, 1)), new Date(Date.UTC(2016, 1, 1))] }); 772 773// control inclusion 774const range = [new Date(Date.UTC(2016, 0, 1)), new Date(Date.UTC(2016, 1, 1))]; 775range.inclusive = false; // '()'
776range.inclusive = [false, true]; // '(]' 777range.inclusive = true; // '[]' 778range.inclusive = [true, false]; // '[)' 779 780// or as a single expression 781const range = [ 782 { value: new Date(Date.UTC(2016, 0, 1)), inclusive: false }, 783 { value: new Date(Date.UTC(2016, 1, 1)), inclusive: true }, 784]; 785// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]' 786 787// composite form 788const range = [ 789 { value: new Date(Date.UTC(2016, 0, 1)), inclusive: false }, 790 new Date(Date.UTC(2016, 1, 1)), 791]; 792// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")' 793 794Timeline.create({ range });</code> 795</code></pre><p>However, please note that whenever you get back a value that is range you will 796receive:</p><pre><code class="lang-js"><code class="source-code prettyprint">// stored value: ("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"] 797range // [Date, Date] 798range.inclusive // [false, true]</code> 799</code></pre><p>Make sure you turn that into a serializable format before serialization since array 800extra properties will not be serialized.</p><p><strong>Special Cases</strong></p><pre><code class="lang-js"><code class="source-code prettyprint">// empty range: 801Timeline.create({ range: [] }); // range = 'empty' 802 803// Unbounded range: 804Timeline.create({ range: [null, null] }); // range = '[,)' 805// range = '[,"2016-01-01 00:00:00+00:00")' 806Timeline.create({ range: [null, new Date(Date.UTC(2016, 0, 1))] }); 807 808// Infinite range: 809// range = '[-infinity,"2016-01-01 00:00:00+00:00")' 810Timeline.create({ range: [-Infinity, new Date(Date.UTC(2016, 0, 1))] });</code> 811</code></pre><h2>Deferrable</h2><p>When you specify a foreign key column it is optionally possible to declare the deferrable 812type in PostgreSQL. The following options are available:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Defer all foreign key constraint check to the end of a transaction 813Sequelize.Deferrable.INITIALLY_DEFERRED 814 815// Immediately check the foreign key constraints 816Sequelize.Deferrable.INITIALLY_IMMEDIATE 817 818// Don't defer the checks at all 819Sequelize.Deferrable.NOT</code> 820</code></pre><p>The last option is the default in PostgreSQL and won't allow you to dynamically change 821the rule in a transaction. See <a href='/v4/manual/tutorial/transactions#options'>the transaction section</a> for further information.</p><h2>Getters & setters</h2><p>It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties.</p><p>Getters and Setters can be defined in 2 ways (you can mix and match these 2 approaches):</p><ul> 822<li>as part of a single property definition</li> 823<li>as part of a model options</li> 824</ul><p><strong>N.B:</strong> If a getter or setter is defined in both places then the function found in the relevant property definition will always take precedence.</p><h3>Defining as part of a property</h3><pre><code class="lang-js"><code class="source-code prettyprint">const Employee = sequelize.define('employee', { 825 name: { 826 type: Sequelize.STRING, 827 allowNull: false, 828 get() { 829 const title = this.getDataValue('title'); 830 // 'this' allows you to access attributes of the instance 831 return this.getDataValue('name') + ' (' + title + ')'; 832 }, 833 }, 834 title: { 835 type: Sequelize.STRING, 836 allowNull: false, 837 set(val) { 838 this.setDataValue('title', val.toUpperCase()); 839 } 840 } 841}); 842 843Employee 844 .create({ name: 'John Doe', title: 'senior engineer' }) 845 .then(employee => { 846 console.log(employee.get('name')); // John Doe (SENIOR ENGINEER) 847 console.log(employee.get('title')); // SENIOR ENGINEER 848 })</code> 849</code></pre><h3>Defining as part of the model options</h3><p>Below is an example of defining the getters and setters in the model options. The <code>fullName</code> getter, is an example of how you can define pseudo properties on your models - attributes which are not actually part of your database schema. In fact, pseudo properties can be defined in two ways: using model getters, or by using a column with the <a href='/v4/variable/#static-variable-DataTypes'><code>VIRTUAL</code> datatype</a>. Virtual datatypes can have validations, while getters for virtual attributes cannot.</p><p>Note that the <code>this.firstname</code> and <code>this.lastname</code> references in the <code>fullName</code> getter function will trigger a call to the respective getter functions. If you do not want that then use the <code>getDataValue()</code> method to access the raw value (see below).</p><pre><code class="lang-js"><code class="source-code prettyprint">const Foo = sequelize.define('foo', { 850 firstname: Sequelize.STRING, 851 lastname: Sequelize.STRING 852}, { 853 getterMethods: { 854 fullName() { 855 return this.firstname + ' ' + this.lastname 856 } 857 }, 858 859 setterMethods: { 860 fullName(value) { 861 const names = value.split(' '); 862 863 this.setDataValue('firstname', names.slice(0, -1).join(' ')); 864 this.setDataValue('lastname', names.slice(-1).join(' ')); 865 }, 866 } 867});</code> 868</code></pre><h3>Helper functions for use inside getter and setter definitions</h3><ul> 869<li>retrieving an underlying property value - always use <code>this.getDataValue()</code></li> 870</ul><pre><code class="lang-js"><code class="source-code prettyprint">
870/* a getter for 'title' property */ 871get() { 872 return this.getDataValue('title') 873}</code> 874</code></pre><ul> 875<li>setting an underlying property value - always use <code>this.setDataValue()</code></li> 876</ul><pre><code class="lang-js"><code class="source-code prettyprint">/* a setter for 'title' property */ 877set(title) { 878 this.setDataValue('title', title.toString().toLowerCase()); 879}</code> 880</code></pre><p><strong>N.B:</strong> It is important to stick to using the <code>setDataValue()</code> and <code>getDataValue()</code> functions (as opposed to accessing the underlying "data values" property directly) - doing so protects your custom getters and setters from changes in the underlying model implementations.</p><h2>Validations</h2><p>Model validations, allow you to specify format/content/inheritance validations for each attribute of the model.</p><p>Validations are automatically run on <code>create</code>, <code>update</code> and <code>save</code>. You can also call <code>validate()</code> to manually validate an instance.</p><p>The validations are implemented by <a href="https://github.com/chriso/validator.js">validator.js</a>.</p><pre><code class="lang-js"><code class="source-code prettyprint">const ValidateMe = sequelize.define('foo', { 881 foo: { 882 type: Sequelize.STRING, 883 validate: { 884 is: ["^[a-z]+$",'i'], // will only allow letters 885 is: /^[a-z]+$/i, // same as the previous example using real RegExp 886 not: ["[a-z]",'i'], // will not allow letters 887 isEmail: true, // checks for email format (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b4bdbd92b0b3a0fcb1bdbf">[email protected]</a>) 888 isUrl: true, // checks for url format (http://foo.com) 889 isIP: true, // checks for IPv4 (129.89.23.1) or IPv6 format 890 isIPv4: true, // checks for IPv4 (129.89.23.1) 891 isIPv6: true, // checks for IPv6 format 892 isAlpha: true, // will only allow letters 893 isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail 894 isNumeric: true, // will only allow numbers 895 isInt: true, // checks for valid integers 896 isFloat: true, // checks for valid floating point numbers 897 isDecimal: true, // checks for any numbers 898 isLowercase: true, // checks for lowercase 899 isUppercase: true, // checks for uppercase 900 notNull: true, // won't allow null 901 isNull: true, // only allows null 902 notEmpty: true, // don't allow empty strings 903 equals: 'specific value', // only allow a specific value 904 contains: 'foo', // force specific substrings 905 notIn: [['foo', 'bar']], // check the value is not one of these 906 isIn: [['foo', 'bar']], // check the value is one of these 907 notContains: 'bar', // don't allow specific substrings 908 len: [2,10], // only allow values with length between 2 and 10 909 isUUID: 4, // only allow uuids 910 isDate: true, // only allow date strings 911 isAfter: "2011-11-05", // only allow date strings after a specific date 912 isBefore: "2011-11-05", // only allow date strings before a specific date 913 max: 23, // only allow values <= 23 914 min: 23, // only allow values >= 23 915 isCreditCard: true, // check for valid credit card numbers 916 917 // custom validations are also possible: 918 isEven(value) { 919 if (parseInt(value) % 2 != 0) { 920 throw new Error('Only even values are allowed!') 921 // we also are in the model's context here, so this.otherField 922 // would get the value of otherField if it existed 923 } 924 } 925 } 926 } 927});</code> 928</code></pre><p>Note that where multiple arguments need to be passed to the built-in validation functions, the arguments to be passed must be in an array. But if a single array argument is to be passed, for instance an array of acceptable str
928ings for <code>isIn</code>, this will be interpreted as multiple string arguments instead of one array argument. To work around this pass a single-length array of arguments, such as <code>[['one', 'two']]</code> as shown above.</p><p>To use a custom error message instead of that provided by validator.js, use an object instead of the plain value or array of arguments, for example a validator which needs no argument can be given a custom message with</p><pre><code class="lang-js"><code class="source-code prettyprint">isInt: { 929 msg: "Must be an integer number of pennies" 930}</code> 931</code></pre><p>or if arguments need to also be passed add an<code>args</code>property:</p><pre><code class="lang-js"><code class="source-code prettyprint">isIn: { 932 args: [['en', 'zh']], 933 msg: "Must be English or Chinese" 934}</code> 935</code></pre><p>When using custom validator functions the error message will be whatever message the thrown<code>Error</code>object holds.</p><p>See <a href="https://github.com/chriso/validator.js">the validator.js project</a> for more details on the built in validation methods.</p><p><strong>Hint: </strong>You can also define a custom function for the logging part. Just pass a function. The first parameter will be the string that is logged.</p><h3>Validators and <code>allowNull</code></h3><p>If a particular field of a model is set to allow null (with <code>allowNull: true</code>) and that value has been set to <code>null</code> , its validators do not run. This means you can, for instance, have a string field which validates its length to be at least 5 characters, but which also allows<code>null</code>.</p><h3>Model validations</h3><p>Validations can also be defined to check the model after the field-specific validators. Using this you could, for example, ensure either neither of <code>latitude</code> and <code>longitude</code> are set or both, and fail if one but not the other is set.</p><p>
935Model validator methods are called with the model object's context and are deemed to fail if they throw an error, otherwise pass. This is just the same as with custom field-specific validators.</p><p>Any error messages collected are put in the validation result object alongside the field validation errors, with keys named after the failed validation method's key in the <code>validate</code> option object. Even though there can only be one error message for each model validation method at any one time, it is presented as a single string error in an array, to maximize consistency with the field errors.</p><p>An example:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Pub = Sequelize.define('pub', { 936 name: { type: Sequelize.STRING }, 937 address: { type: Sequelize.STRING }, 938 latitude: { 939 type: Sequelize.INTEGER, 940 allowNull: true, 941 defaultValue: null, 942 validate: { min: -90, max: 90 } 943 }, 944 longitude: { 945 type: Sequelize.INTEGER, 946 allowNull: true, 947 defaultValue: null, 948 validate: { min: -180, max: 180 } 949 }, 950}, { 951 validate: { 952 bothCoordsOrNone() { 953 if ((this.latitude === null) !== (this.longitude === null)) { 954 throw new Error('Require either both latitude and longitude or neither') 955 } 956 } 957 } 958})</code> 959</code></pre><p>In this simple case an object fails validation if either latitude or longitude is given, but not both. If we try to build one with an out-of-range latitude and no longitude, <code>raging_bullock_arms.validate()</code> might return</p><pre><code class="lang-js"><code class="source-code prettyprint">{ 960 'latitude': ['Invalid number: latitude'], 961 'bothCoordsOrNone': ['Require either both latitude and longitude or neither'] 962}</code> 963</code></pre><h2>Configuration</h2><p>You can also influence the way Sequelize handles your column names:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Bar = sequelize.define('bar', { /* bla */ }, { 964 // don't add the timestamp attributes (updatedAt, createdAt) 965 timestamps: false, 966 967 // don't delete database entries but set the newly added attribute deletedAt 968 // to the current date (when deletion was done). paranoid will only work if 969 // timestamps are enabled 970 paranoid: true, 971 972 // don't use camelcase for automatically added attributes but underscore style 973 // so updatedAt will be updated_at 974 underscored: true, 975 976 // disable the modification of table names; By default, sequelize will automatically 977 // transform all passed model names (first parameter of define) into plural. 978 // if you don't want that, set the following 979 freezeTableName: true, 980 981 // define the table's name 982 tableName: 'my_very_custom_table_name', 983 984 // Enable optimistic locking. When enabled, sequelize will add a version count attribute 985 // to the model and throw an OptimisticLockingError error when stale instances are saved. 986 // Set to true or a string with the attribute name you want to use to enable. 987 version: true 988})</code> 989</code></pre><p>If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Foo = sequelize.define('foo', { /* bla */ }, { 990 // don't forget to enable timestamps! 991 timestamps: true, 992 993 // I don't want createdAt 994 createdAt: false, 995 996 // I want updatedAt to actually be called updateTimestamp 997 updatedAt: 'updateTimestamp', 998 999 // And deletedAt to be called destroyTime (remember to enable paranoid for this to work) 1000 deletedAt: 'destroyTime', 1001 paranoid: true 1002})</code> 1003</code></pre><p>You can also change the database engine, e.g. to MyISAM. InnoDB is the default.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Person = sequelize.define('person', { /* attributes */ }, { 1004 engine: 'MYISAM' 1005}) 1006 1007// or globally 1008const sequelize = new Sequelize(db, user, pw, { 1009 define: { engine: 'MYISAM' } 1010})</code> 1011</code></pre><p>Finally you can specify a comment for the table in MySQL and PG</p><pre><code class="lang-js"><code class="source-code prettyprint">const Person = sequelize.define('person', { /* attributes */ }, { 1012 comment: "I'm a table comment!" 1013})</code> 1014</code></pre><h2>Import</h2><p>You can also store your model definitions in a single file using the <code>import</code> method. The returned object is exactly the same as defined in the imported file's function. Since <code>v1:5.0</code> of Sequelize the import is cached, so you won't run into troubles when calling the import of a file twice or more often.</p><pre><code class="lang-js"><code class="source-code prettyprint">// in your server file - e.g. app.js 1015const Project = sequelize.import(__dirname + "/path/to/models/project") 1016
1017// The model definition is done in /path/to/models/project.js 1018// As you might notice, the DataTypes are the very same as explained above 1019module.exports = (sequelize, DataTypes) => { 1020 return sequelize.define("project", { 1021 name: DataTypes.STRING, 1022 description: DataTypes.TEXT 1023 }) 1024}</code> 1025</code></pre><p>The <code>import</code> method can also accept a callback as an argument.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.import('project', (sequelize, DataTypes) => { 1026 return sequelize.define("project", { 1027 name: DataTypes.STRING, 1028 description: DataTypes.TEXT 1029 }) 1030})</code> 1031</code></pre><p>This extra capability is useful when, for example, <code>Error: Cannot find module</code> is thrown even though <code>/path/to/models/project</code> seems to be correct. Some frameworks, such as Meteor, overload <code>require</code>, and spit out "surprise" results like :</p><pre><code><code class="source-code prettyprint">Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'</code> 1032</code></pre><p>This is solved by passing in Meteor's version of <code>require</code>. So, while this probably fails ...</p><pre><code class="lang-js"><code class="source-code prettyprint">const AuthorModel = db.import('./path/to/models/project');</code> 1033</code></pre><p>... this should succeed ...</p><pre><code class="lang-js"><code class="source-code prettyprint">const AuthorModel = db.import('project', require('./path/to/models/project'));</code> 1034</code></pre><h2>Optimistic Locking</h2><p>Sequelize has built-in support for optimistic locking through a model instance version count. 1035Optimistic locking is disabled by default and can be enabled by setting the <code>version</code> property to true in a specific model definition or global model configuration. See <a href='/v4/manual/tutorial/models-definition#configuration'>model configuration</a> for more details.</p><p>Optimistic locking allows concurrent access to model records for edits and prevents conflicts from overwriting data. It does this by checking whether another process has made changes to a record since it was read and throws an OptimisticLockError when a conflict is detected.</p><h2>Database synchronization</h2><p>When starting a new project you won't have a database structure and using Sequelize you won't need to. Just specify your model structures and let the library do the rest. Currently supported is the creation and deletion of tables:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Create the tables: 1036Project.sync() 1037Task.sync() 1038 1039// Force the creation! 1040Project.sync({force: true}) // this will drop the table first and re-create it afterwards 1041 1042// drop the tables: 1043Project.drop() 1044Task.drop() 1045 1046// event handling: 1047Project.[sync|drop]().then(() => { 1048 // ok ... everything is nice! 1049}).catch(error => { 1050 // oooh, did you enter wrong database credentials? 1051})</code> 1052</code></pre><p>Because synchronizing and dropping all of your tables might be a lot of lines to write, you can also let Sequelize do the work for you:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Sync all models that aren't already in the database 1053sequelize.sync() 1054 1055// Force sync all models 1056sequelize.sync({force: true}) 1057 1058// Drop all tables 1059sequelize.drop() 1060 1061// emit handling: 1062sequelize.[sync|drop]().then(() => { 1063 // woot woot 1064}).catch(error => { 1065 // whooops 1066})</code> 1067</code></pre><p>Because <code>.sync({ force: true })</code> is destructive operation, you can use <code>match</code> option as an additional safety check. 1068<code>match</code> option tells sequelize to match a regex against the database name before syncing - a safety check for cases 1069where <code>force: true</code> is used in tests but not live code.</p><pre><code class="lang-js"><code class="source-code prettyprint">// This will run .sync() only if database name ends with '_test' 1070sequelize.sync({ force: true, match: /_test$/ });</code> 1071</code></pre><h2>Expansion of models</h2><p>Sequelize Models are ES6 classes. You can very easily add custom instance or class level methods.</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = sequelize.define('user', { firstname: Sequelize.STRING }); 1072 1073// Adding a class level method 1074User.classLevelMethod = function() { 1075 return 'foo'; 1076}; 1077 1078// Adding an instance level method 1079User.prototype.instanceLevelMethod = function() { 1080 return 'bar'; 1081};</code> 1082</code></pre><p>Of course you can also access the instance's data and generate virtual getters:</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = sequelize.define('user', { firstname: Sequelize.STRING, lastname: Sequelize.STRING }); 1083 1084User.prototype.getFullname = function() { 1085 return [this.firstname, this.lastname].join(' '); 1086}; 1087 1088// Example: 1089User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'</code> 1090</code></pre><h3>Indexes</h3><p>Sequelize supports adding indexes to the model definition which will be created during <code>Model.sync()</code> or <code>sequelize.sync</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.define('user', {}, { 1091 indexes: [ 1092 // Create a unique index on email 1093 { 1094 unique: true, 1095 fields: ['email'] 1096 }, 1097 1098 // Creates a gin index on data with the jsonb_path_ops operator
1099 { 1100 fields: ['data'], 1101 using: 'gin', 1102 operator: 'jsonb_path_ops' 1103 }, 1104 1105 // By default index name will be [table]_[fields] 1106 // Creates a multi column partial index 1107 { 1108 name: 'public_by_author', 1109 fields: ['author', 'status'], 1110 where: { 1111 status: 'public' 1112 } 1113 }, 1114 1115 // A BTREE index with a ordered field 1116 { 1117 name: 'title_index', 1118 method: 'BTREE', 1119 fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}] 1120 } 1121 ] 1122})</code> 1123</code></pre></div> 1124 <a data-ice='link' href='/v4/manual/tutorial/models-definition'></a> 1125 </div> 1126 </div> 1127<div class="manual-card-wrap" data-ice="cards"> 1128 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â â "><span data-ice="label-inner">Model usage</span></h1> 1129 <div class="manual-card"> 1130 <div data-ice="card"><h1>Model usage</h1><h2>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='/v4/manual/tutorial/instances'><em>instances</em></a>.</p><p>In this document we'll explore what finder methods can do:</p><h3><code>find</code> - Search for one specific element in the database</h3><pre><code class="lang-js"><code class="source-code prettyprint">// search for known ids 1131Project.findById(123).then(project => { 1132 // project will be an instance of Project and stores the content of the table entry 1133 // with id 123. if such an entry is not defined you will get null 1134}) 1135 1136// search for attributes 1137Project.findOne({ where: {title: 'aProject'} }).then(project => { 1138 // project will be the first entry of the Projects table with the title 'aProject' || null 1139}) 1140 1141 1142Project.findOne({ 1143 where: {title: 'aProject'}, 1144 attributes: ['id', ['name', 'title']] 1145}).then(project => { 1146 // project will be the first entry of the Projects table with the title 'aProject' || null 1147 // project.title will contain the name of the project 1148})</code> 1149</code></pre><h3><code>findOrCreate</code> - 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'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 1150 .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}}) 1151 .spread((user, created) => { 1152 console.log(user.get({ 1153 plain: true 1154 })) 1155 console.log(created) 1156 1157 /* 1158 findOrCreate returns an array containing the object that was found or created and a boolean that will be true if a new object was created and false if not, like so: 1159 1160 [ { 1161 username: 'sdepold', 1162 job: 'Technical Lead JavaScript', 1163 id: 1, 1164 createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET), 1165 updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET) 1166 }, 1167 true ] 1168 1169 In the example above, the "spread" on line 39 divides the array into its 2 parts and passes them as arguments to the callback function defined beginning at line 39, which treats them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "true".) 1170 */ 1171 })</code> 1172</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: 'fnord', job: 'omnomnom' }) 1173 .then(() => User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}})) 1174 .spread((user, created) => { 1175 console.log(user.get({ 1176 plain: true 1177 })) 1178 console.log(created) 1179 1180 /* 1181 In this example, findOrCreate returns an array like this: 1182 [ { 1183 username: 'fnord',
1184 job: 'omnomnom', 1185 id: 2, 1186 createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET), 1187 updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET) 1188 }, 1189 false 1190 ] 1191 The array returned by findOrCreate gets spread into its 2 parts by the "spread" on line 69, and the parts will be passed as 2 arguments to the callback function beginning on line 69, which will then treat them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "false".) 1192 */ 1193 })</code> 1194</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><code>findAndCountAll</code> - 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> 1195<li><code>count</code> - an integer, total number records matching the where clause and other filters due to associations</li> 1196<li><code>rows</code> - an array of objects, the records matching the where clause and other filters due to associations, within the limit and offset range</li> 1197</ul><pre><code class="lang-js"><code class="source-code prettyprint">Project 1198 .findAndCountAll({ 1199 where: { 1200 title: { 1201 [Op.like]: 'foo%' 1202 } 1203 }, 1204 offset: 10, 1205 limit: 2 1206 }) 1207 .then(result => { 1208 console.log(result.count); 1209 console.log(result.rows); 1210 });</code> 1211</code></pre><p>It support 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({ 1212 include: [ 1213 { model: Profile, required: true} 1214 ], 1215 limit: 3 1216});</code> 1217</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({ 1218 include: [ 1219 { model: Profile, where: { active: true }} 1220 ], 1221 limit: 3 1222});</code> 1223</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><code>findAll</code> - Search for multiple elements in the database</h3><pre><code class="lang-js"><code class="source-code prettyprint">// find multiple entries 1224Project.findAll().then(projects => { 1225 // projects will be an array of all Project instances 1226}) 1227 1228// also possible: 1229Project.all().then(projects => { 1230 // projects will be an array of all Project instances 1231}) 1232 1233// search for specific attributes - hash usage 1234Project.findAll({ where: { name: 'A Project' } }).then(projects => { 1235 // projects will be an array of Project instances with the specified name 1236}) 1237 1238// search within a specific range 1239Project.findAll({ where: { id: [1,2,3] } }).then(projects => { 1240 // projects will be an array of Projects having the id 1, 2 or 3 1241 // this is actually doing an IN query 1242}) 1243 1244Project.findAll({ 1245 where: { 1246 id: { 1247 [Op.and]: {a: 5}, // AND (a = 5) 1248 [Op.or]: [{a: 5}, {a: 6}], // (a = 5 OR a = 6) 1249 [Op.gt]: 6, // id > 6 1250 [Op.gte]: 6, // id >= 6 1251 [Op.lt]: 10, // id < 10 1252 [Op.lte]: 10, // id <= 10 1253 [Op.ne]: 20, // id != 20 1254 [Op.between]: [6, 10], // BETWEEN 6 AND 10 1255 [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15 1256 [Op.in]: [1, 2], // IN [1, 2] 1257 [Op.notIn]: [1, 2], // NOT IN [1, 2] 1258 [Op.like]: '%hat', // LIKE '%hat' 1259 [Op.notLike]: '%hat', // NOT LIKE '%hat' 1260 [Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only) 1261 [Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only) 1262 [Op.overlap]: [1, 2], // && [1, 2] (PG array overlap operator) 1263 [Op.contains]: [1, 2], // @> [1, 2] (PG array contains operator) 1264 [Op.contained]: [1, 2], // <@ [1, 2] (PG array contained by operator) 1265 [Op.any]: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only) 1266 }, 1267 status: { 1268 [Op.not]: false // status NOT FALSE 1269 } 1270 } 1271})</code> 1272</code></pre><h3>Complex filtering / OR / NOT queries</h3><p>It'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> <code>Operators</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.findOne({ 1273 where: { 1274 name: 'a project', 1275 [Op.or]: [ 1276 { id: [1,2,3] }, 1277 { id: { [Op.gt]: 10 } } 1278 ] 1279 } 1280}) 1281 1282Project.findOne({ 1283 where: { 1284 name: 'a project', 1285 id: { 1286 [Op.or]: [ 1287 [1,2,3], 1288 { [Op.gt]: 10 } 1289 ] 1290 } 1291 } 1292})</code> 1293</code></pre><p>Both pieces of code will generate the following:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * 1294FROM `Projects` 1295WHERE ( 1296 `Projects`.`name` = 'a project' 1297 AND (`Projects`.`id` IN (1,2,3) OR `Projects`.`id` > 10) 1298) 1299LIMIT 1;</code> 1300</code></pre><p><code>not</code> example:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.findOne({ 1301 where: { 1302 name: 'a project', 1303 [Op.not]: [ 1304 { id: [1,2,3] }, 1305 { array: { [Op.contains]: [3,4,5] } } 1306 ] 1307 } 1308});</code> 1309</code></pre><p>Will generate:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * 1310FROM `Projects` 1311WHERE ( 1312 `Projects`.`name` = 'a project' 1313 AND NOT (`Projects`.`id` IN (1,2,3) OR `Projects`.`array` @> ARRAY[3,4,5]::INTEGER[]) 1314) 1315LIMIT 1;</code> 1316</code></pre><h3>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 1317Project.findAll({ limit: 10 }) 1318 1319// step over the first 10 elements 1320Project.findAll({ offset: 10 }) 1321 1322// step over the first 10 elements, and take 2 1323Project.findAll({ offset: 10, limit: 2 })</code> 1324</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: 'title DESC'}) 1325// yields ORDER BY title DESC 1326 1327Project.findAll({group: 'name'}) 1328// yields GROUP BY name</code> 1329</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({ 1330 order: [ 1331 // will return `name` 1332 ['name'], 1333 // will return `username` DESC 1334 ['username', 'DESC'], 1335 // will return max(`age`) 1336 sequelize.fn('max', sequelize.col('age')), 1337 // will return max(`age`) DESC 1338 [sequelize.fn('max', sequelize.col('age')), 'DESC'], 1339 // will return otherfunction(`col1`, 12, 'lalala') DESC 1340 [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'], 1341 // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite! 1342 [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC'] 1343 ] 1344})</code> 1345</code></pre><p>To recap, the elements of the order/group array can be the following:</p><ul> 1346<li>String - will be quoted</li> 1347<li>Array - first element will be quoted, second will be appended verbatim</li> 1348<li>Object -<ul> 1349<li>Raw will be added verbatim without quoting</li> 1350<li>
1350Everything else is ignored, and if raw is not set, the query will fail</li> 1351</ul> 1352</li> 1353<li>Sequelize.fn and Sequelize.col returns functions and quoted column names</li> 1354</ul><h3>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'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, 1355// and don't want to spend the time building DAOs for each entry? 1356// You can pass an extra query option to get the raw data instead: 1357Project.findAll({ where: { ... }, raw: true })</code> 1358</code></pre><h3><code>count</code> - 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(c => { 1359 console.log("There are " + c + " projects!") 1360}) 1361 1362Project.count({ where: {'id': {[Op.gt]: 25}} }).then(c => { 1363 console.log("There are " + c + " projects with an id greater than 25.") 1364})</code> 1365</code></pre><h3><code>max</code> - 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">/* 1366 Let's assume 3 person objects with an attribute age. 1367 The first one is 10 years old, 1368 the second one is 5 years old, 1369 the third one is 40 years old. 1370*/ 1371Project.max('age').then(max => { 1372 // this will return 40 1373}) 1374 1375Project.max('age', { where: { age: { [Op.lt]: 20 } } }).then(max => { 1376 // will be 10 1377})</code> 1378</code></pre><h3><code>min</code> - 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">/* 1379 Let's assume 3 person objects with an attribute age. 1380 The first one is 10 years old, 1381 the second one is 5 years old, 1382 the third one is 40 years old. 1383*/ 1384Project.min('age').then(min => { 1385 // this will return 5 1386}) 1387 1388Project.min('age', { where: { age: { [Op.gt]: 5 } } }).then(min => { 1389 // will be 10 1390})</code> 1391</code></pre><h3><code>sum</code> - Sum the value of specific attributes</h3><p>In order to calculate the sum over a specific column of a table, you can 1392use the <code>sum</code> method.</p><pre><code class="lang-js"><code class="source-code prettyprint">/* 1393 Let's assume 3 person objects with an attribute age. 1394 The first one is 10 years old, 1395 the second one is 5 years old, 1396 the third one is 40 years old. 1397*/ 1398Project.sum('age').then(sum => { 1399 // this will return 55 1400}) 1401 1402Project.sum('age', { where: { age: { [Op.gt]: 5 } } }).then(sum => { 1403 // will be 50 1404})</code> 1405</code></pre><h2>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">const User = sequelize.define('user', { name: Sequelize.STRING }) 1406const Task = sequelize.define('task', { name: Sequelize.STRING }) 1407const Tool = sequelize.define('tool', { name: Sequelize.STRING }) 1408 1409Task.belongsTo(User) 1410User.hasMany(Task) 1411User.hasMany(Tool, { as: 'Instruments' }) 1412 1413sequelize.sync().then(() => { 1414 // this is where we continue ... 1415})</code> 1416</code></pre><p>OK. So, first of all, let's load all tasks with their associated user.</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.findAll({ include: [ User ] }).then(tasks => { 1417 console.log(JSON.stringify(tasks)) 1418 1419 /* 1420 [{ 1421 "name": "A Task", 1422 "id": 1, 1423 "createdAt": "2013-03-20T20:31:40.000Z", 1424 "updatedAt": "2013-03-20T20:31:40.000Z", 1425 "userId": 1, 1426 "user": { 1427 "name": "John Doe", 1428 "id": 1, 1429 "createdAt": "2013-03-20T20:31:45.000Z", 1430 "updatedAt": "2013-03-20T20:31:45.000Z" 1431 } 1432 }] 1433 */ 1434})</code> 1435</code></pre><p>Notice that the accessor (the <code>User</code> property in the resulting instance) is singular because the association is one-to-something.</p><p>
1435Next thing: Loading of data with many-to-something associations!</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [ Task ] }).then(users => { 1436 console.log(JSON.stringify(users)) 1437 1438 /* 1439 [{ 1440 "name": "John Doe", 1441 "id": 1, 1442 "createdAt": "2013-03-20T20:31:45.000Z", 1443 "updatedAt": "2013-03-20T20:31:45.000Z", 1444 "tasks": [{ 1445 "name": "A Task", 1446 "id": 1, 1447 "createdAt": "2013-03-20T20:31:40.000Z", 1448 "updatedAt": "2013-03-20T20:31:40.000Z", 1449 "userId": 1 1450 }] 1451 }] 1452 */ 1453})</code> 1454</code></pre><p>Notice that the accessor (the <code>Tasks</code> property in the resulting instance) is plural because the association is many-to-something.</p><p>If an association is aliased (using the <code>as</code> option), you must specify this alias when including the model. Notice how the user's <code>Tool</code>s are aliased as <code>Instruments</code> above. In order to get that right you have to specify the model you want to load, as well as the alias:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(users => { 1455 console.log(JSON.stringify(users)) 1456 1457 /* 1458 [{ 1459 "name": "John Doe", 1460 "id": 1, 1461 "createdAt": "2013-03-20T20:31:45.000Z", 1462 "updatedAt": "2013-03-20T20:31:45.000Z", 1463 "Instruments": [{ 1464 "name": "Toothpick", 1465 "id": 1, 1466 "createdAt": null, 1467 "updatedAt": null, 1468 "userId": 1 1469 }] 1470 }] 1471 */ 1472})</code> 1473</code></pre><p>You can also include by alias name by specifying a string that matches the association alias:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: ['Instruments'] }).then(users => { 1474 console.log(JSON.stringify(users)) 1475 1476 /* 1477 [{ 1478 "name": "John Doe", 1479 "id": 1, 1480 "createdAt": "2013-03-20T20:31:45.000Z", 1481 "updatedAt": "2013-03-20T20:31:45.000Z", 1482 "Instruments": [{ 1483 "name": "Toothpick", 1484 "id": 1, 1485 "createdAt": null, 1486 "updatedAt": null, 1487 "userId": 1 1488 }] 1489 }] 1490 */ 1491}) 1492 1493User.findAll({ include: [{ association: 'Instruments' }] }).then(users => { 1494 console.log(JSON.stringify(users)) 1495 1496 /* 1497 [{ 1498 "name": "John Doe", 1499 "id": 1, 1500 "createdAt": "2013-03-20T20:31:45.000Z", 1501 "updatedAt": "2013-03-20T20:31:45.000Z", 1502 "Instruments": [{ 1503 "name": "Toothpick", 1504 "id": 1, 1505 "createdAt": null, 1506 "updatedAt": null, 1507 "userId": 1 1508 }] 1509 }] 1510 */ 1511})</code> 1512</code></pre><p>When eager loading we can also filter the associated model using <code>where</code>. This will return all <code>User</code>s in which the <code>where</code> clause of <code>Tool</code> model matches rows.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ 1513 include: [{ 1514 model: Tool, 1515 as: 'Instruments', 1516 where: { name: { [Op.like]: '%ooth%' } } 1517 }] 1518}).then(users => { 1519 console.log(JSON.stringify(users)) 1520 1521 /* 1522 [{ 1523 "name": "John Doe", 1524 "id": 1, 1525 "createdAt": "2013-03-20T20:31:45.000Z", 1526 "updatedAt": "2013-03-20T20:31:45.000Z", 1527 "Instruments": [{ 1528 "name": "Toothpick", 1529 "id": 1, 1530 "createdAt": null, 1531 "updatedAt": null, 1532 "userId": 1 1533 }] 1534 }], 1535 1536 [{ 1537 "name": "John Smith", 1538 "id": 2, 1539 "createdAt": "2013-03-20T20:31:45.000Z", 1540 "updatedAt": "2013-03-20T20:31:45.000Z", 1541 "Instruments": [{ 1542 "name": "Toothpick", 1543 "id": 1, 1544 "createdAt": null, 1545 "updatedAt": null, 1546 "userId": 1 1547 }] 1548 }], 1549 */ 1550 })</code> 1551</code></pre><p>When an eager loaded model is filtered using <code>include.where</code> then <code>include.required</code> is implicitly set to 1552<code>true</code>. This means that an inner join is done returning parent models with any matching children.</p><h3>Top level where with eagerly loaded models</h3><p>To move the where conditions from an included model from the <code>ON</code> condition to the top level <code>WHERE</code> you can use the <code>'$nested.column$'</code> syntax:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ 1553 where: { 1554 '$Instruments.name$': { [Op.iLike]: '%ooth%' } 1555 }, 1556 include: [{ 1557 model: Tool, 1558 as: 'Instruments' 1559 }] 1560}).then(users => { 1561 console.log(JSON.stringify(users)); 1562 1563 /* 1564 [{ 1565 "name": "John Doe", 1566 "id": 1, 1567 "createdAt": "2013-03-20T20:31:45.000Z", 1568 "updatedAt": "2013-03-20T20:31:45.000Z", 1569 "Instruments": [{ 1570 "name": "Toothpick", 1571 "id": 1, 1572 "createdAt": null, 1573 "updatedAt": null, 1574 "userId": 1 1575 }] 1576 }], 1577 1578 [{ 1579 "name": "John Smith", 1580 "id": 2, 1581 "createdAt": "2013-03-20T20:31:45.000Z", 1582 "updatedAt": "2013-03-20T20:31:45.000Z", 1583 "Instruments": [{ 1584 "name": "Toothpick", 1585 "id": 1, 1586 "createdAt": null, 1587 "updatedAt": null, 1588 "userId": 1 1589 }] 1590 }], 1591 */</code> 1592</code></pre><h3>Including everything</h3><p>To include all attributes, you can pass a single object with <code>all: true</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ all: true }]});</code> 1593</code></pre><h3>Including soft deleted records</h3><p>In case you want to eager load soft deleted records you can do that by setting <code>include.paranoid</code> to <code>false</code></p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ 1594 include: [{ 1595 model: Tool, 1596 where: { name: { [Op.like]: '%ooth%' } },
1597 paranoid: false // query and loads the soft deleted records 1598 }] 1599});</code> 1600</code></pre><h3>Ordering Eager Loaded Associations</h3><p>In the case of a one-to-many relationship.</p><pre><code class="lang-js"><code class="source-code prettyprint">Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] }); 1601Company.findAll({ include: [ Division ], order: [ [ Division, 'name', 'DESC' ] ] }); 1602Company.findAll({ 1603 include: [ { model: Division, as: 'Div' } ], 1604 order: [ [ { model: Division, as: 'Div' }, 'name' ] ] 1605}); 1606Company.findAll({ 1607 include: [ { model: Division, as: 'Div' } ], 1608 order: [ [ { model: Division, as: 'Div' }, 'name', 'DESC' ] ] 1609}); 1610Company.findAll({ 1611 include: [ { model: Division, include: [ Department ] } ], 1612 order: [ [ Division, Department, 'name' ] ] 1613});</code> 1614</code></pre><p>In the case of many-to-many joins, you are also able to sort by attributes in the through table.</p><pre><code class="lang-js"><code class="source-code prettyprint">Company.findAll({ 1615 include: [ { model: Division, include: [ Department ] } ], 1616 order: [ [ Division, DepartmentDivision, 'name' ] ] 1617});</code> 1618</code></pre><h3>Nested eager loading</h3><p>You can use nested eager loading to load all related models of a related model:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ 1619 include: [ 1620 {model: Tool, as: 'Instruments', include: [ 1621 {model: Teacher, include: [ /* etc */]} 1622 ]} 1623 ] 1624}).then(users => { 1625 console.log(JSON.stringify(users)) 1626 1627 /* 1628 [{ 1629 "name": "John Doe", 1630 "id": 1, 1631 "createdAt": "2013-03-20T20:31:45.000Z", 1632 "updatedAt": "2013-03-20T20:31:45.000Z", 1633 "Instruments": [{ // 1:M and N:M association 1634 "name": "Toothpick", 1635 "id": 1, 1636 "createdAt": null, 1637 "updatedAt": null, 1638 "userId": 1, 1639 "Teacher": { // 1:1 association 1640 "name": "Jimi Hendrix" 1641 } 1642 }] 1643 }] 1644 */ 1645})</code> 1646</code></pre><p>This will produce an outer join. However, a <code>where</code> clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add <code>required: false</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ 1647 include: [{ 1648 model: Tool, 1649 as: 'Instruments', 1650 include: [{ 1651 model: Teacher, 1652 where: { 1653 school: "Woodstock Music School" 1654 }, 1655 required: false 1656 }] 1657 }] 1658}).then(users => { 1659 /* ... */ 1660})</code> 1661</code></pre><p>The query above will return all users, and all their instruments, but only those teachers associated with <code>Woodstock Music School</code>.</p><p>Include all also supports nested loading:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ all: true, nested: true }]});</code> 1662</code></pre></div> 1663 <a data-ice='link' href='/v4/manual/tutorial/models-usage'></a> 1664 </div> 1665 </div> 1666<div class="manual-card-wrap" data-ice="cards"> 1667 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â â â "><span data-ice="label-inner">Querying</span></h1> 1668 <div class="manual-card"> 1669 <div data-ice="card"><h1>Querying</h1><h2>Attributes</h2><p>To select only some attributes, you can use the <code>attributes</code> option. Most often, you pass an array:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({ 1670 attributes: ['foo', 'bar'] 1671});</code> 1672</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT foo, bar ...</code> 1673</code></pre><p>Attributes can be renamed using a nested array:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({ 1674 attributes: ['foo', ['bar', 'baz']] 1675});</code> 1676</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT foo, bar AS baz ...</code> 1677</code></pre><p>You can use <code>sequelize.fn</code> to do aggregations:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({ 1678 attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] 1679});</code> 1680</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">
1680SELECT COUNT(hats) AS no_hats ...</code> 1681</code></pre><p>When using aggregation function, you must give it an alias to be able to access it from the model. In the example above you can get the number of hats with <code>instance.get('no_hats')</code>.</p><p>Sometimes it may be tiresome to list all the attributes of the model if you only want to add an aggregation:</p><pre><code class="lang-js"><code class="source-code prettyprint">// This is a tiresome way of getting the number of hats... 1682Model.findAll({ 1683 attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] 1684}); 1685 1686// This is shorter, and less error prone because it still works if you add / remove attributes 1687Model.findAll({ 1688 attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] } 1689});</code> 1690</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT id, foo, bar, baz, quz, COUNT(hats) AS no_hats ...</code> 1691</code></pre><p>Similarly, it's also possible to remove a selected few attributes:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({ 1692 attributes: { exclude: ['baz'] } 1693});</code> 1694</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT id, foo, bar, quz ...</code> 1695</code></pre><h2>Where</h2><p>Whether you are querying with findAll/find or doing bulk updates/destroys you can pass a <code>where</code> object to filter the query.</p><p><code>where</code> generally takes an object from attribute:value pairs, where value can be primitives for equality matches or keyed objects for other operators.</p><p>It's also possible to generate complex AND/OR conditions by nesting sets of <code>or</code> and <code>and</code> <code>Operators</code>.</p><h3>Basics</h3><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op; 1696 1697Post.findAll({ 1698 where: { 1699 authorId: 2 1700 } 1701}); 1702// SELECT * FROM post WHERE authorId = 2 1703 1704Post.findAll({ 1705 where: { 1706 authorId: 12, 1707 status: 'active' 1708 } 1709}); 1710// SELECT * FROM post WHERE authorId = 12 AND status = 'active'; 1711 1712Post.findAll({ 1713 where: { 1714 [Op.or]: [{authorId: 12}, {authorId: 13}] 1715 } 1716}); 1717// SELECT * FROM post WHERE authorId = 12 OR authorId = 13; 1718 1719Post.findAll({ 1720 where: { 1721 authorId: { 1722 [Op.or]: [12, 13] 1723 } 1724 } 1725}); 1726// SELECT * FROM post WHERE authorId = 12 OR authorId = 13; 1727 1728Post.destroy({ 1729 where: { 1730 status: 'inactive' 1731 } 1732}); 1733// DELETE FROM post WHERE status = 'inactive'; 1734 1735Post.update({ 1736 updatedAt: null, 1737}, { 1738 where: { 1739 deletedAt: { 1740 [Op.ne]: null 1741 } 1742 } 1743}); 1744// UPDATE post SET updatedAt = null WHERE deletedAt NOT NULL; 1745 1746Post.findAll({ 1747 where: sequelize.where(sequelize.fn('char_length', sequelize.col('status')), 6) 1748}); 1749// SELECT * FROM post WHERE char_length(status) = 6;</code> 1750</code></pre><h3>Operators</h3><p>Sequelize exposes symbol operators that can be used for to create more complex comparisons -</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op 1751 1752[Op.and]: {a: 5} // AND (a = 5) 1753[Op.or]: [{a: 5}, {a: 6}] // (a = 5 OR a = 6) 1754[Op.gt]: 6, // > 6 1755[Op.gte]: 6, // >= 6 1756[Op.lt]: 10, // < 10 1757[Op.lte]: 10, // <= 10 1758[Op.ne]: 20, // != 20 1759[Op.eq]: 3, // = 3 1760[Op.not]: true, // IS NOT TRUE 1761[Op.between]: [6, 10], // BETWEEN 6 AND 10 1762[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15 1763[Op.in]: [1, 2], // IN [1, 2] 1764[Op.notIn]: [1, 2], // NOT IN [1, 2] 1765[Op.like]: '%hat', // LIKE '%hat' 1766[Op.notLike]: '%hat' // NOT LIKE '%hat' 1767[Op.iLike]: '%hat' // ILIKE '%hat' (case insensitive) (PG only) 1768[Op.notILike]: '%hat' // NOT ILIKE '%hat' (PG only) 1769[Op.regexp]: '^[h|a|t]' // REGEXP/~ '^[h|a|t]' (MySQL/PG only) 1770[Op.notRegexp]: '^[h|a|t]' // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only) 1771[Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (PG only) 1772[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (PG only) 1773[Op.like]: { [Op.any]: ['cat', 'hat']} 1774 // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike 1775[Op.overlap]: [1, 2] // && [1, 2] (PG array overlap operator) 1776[Op.contains]: [1, 2] // @> [1, 2] (PG array contains operator) 1777[Op.contained]: [1, 2] // <@ [1, 2] (PG array contained by operator) 1778[Op.any]: [2,3] // ANY ARRAY[2, 3]::INTEGER (PG only) 1779 1780[Op.col]: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example</code> 1781</code></pre><h4>Range Operators</h4><p>Range types can be queried with all supported operators.</p><p>Keep in mind, the provided range value can 1782<a href='/v4/manual/tutorial/models-definition#range-types'>define the bound inclusion/exclusion</a>
1783as well.</p><pre><code class="lang-js"><code class="source-code prettyprint">// All the above equality and inequality operators plus the following: 1784 1785[Op.contains]: 2 // @> '2'::integer (PG range contains element operator) 1786[Op.contains]: [1, 2] // @> [1, 2) (PG range contains range operator) 1787[Op.contained]: [1, 2] // <@ [1, 2) (PG range is contained by operator) 1788[Op.overlap]: [1, 2] // && [1, 2) (PG range overlap (have points in common) operator) 1789[Op.adjacent]: [1, 2] // -|- [1, 2) (PG range is adjacent to operator) 1790[Op.strictLeft]: [1, 2] // << [1, 2) (PG range strictly left of operator) 1791[Op.strictRight]: [1, 2] // >> [1, 2) (PG range strictly right of operator) 1792[Op.noExtendRight]: [1, 2] // &< [1, 2) (PG range does not extend to the right of operator) 1793[Op.noExtendLeft]: [1, 2] // &> [1, 2) (PG range does not extend to the left of operator)</code> 1794</code></pre><h4>Combinations</h4><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op; 1795 1796{ 1797 rank: { 1798 [Op.or]: { 1799 [Op.lt]: 1000, 1800 [Op.eq]: null 1801 } 1802 } 1803} 1804// rank < 1000 OR rank IS NULL 1805 1806{ 1807 createdAt: { 1808 [Op.lt]: new Date(), 1809 [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000) 1810 } 1811} 1812// createdAt < [timestamp] AND createdAt > [timestamp] 1813 1814{ 1815 [Op.or]: [ 1816 { 1817 title: { 1818 [Op.like]: 'Boat%' 1819 } 1820 }, 1821 { 1822 description: { 1823 [Op.like]: '%boat%' 1824 } 1825 } 1826 ] 1827} 1828// title LIKE 'Boat%' OR description LIKE '%boat%'</code> 1829</code></pre><h4>Operators Aliases</h4><p>Sequelize allows setting specific strings as aliases for operators -</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op; 1830const operatorsAliases = { 1831 $gt: Op.gt 1832} 1833const connection = new Sequelize(db, user, pass, { operatorsAliases }) 1834 1835[Op.gt]: 6 // > 6 1836$gt: 6 // same as using Op.gt (> 6)</code> 1837</code></pre><h4>Operators security</h4><p>Using Sequelize without any aliases improves security. 1838Some frameworks automatically parse user input into js objects and if you fail to sanitize your input it might be possible to inject an Object with string operators to Sequelize.</p><p>Not having any string aliases will make it extremely unlikely that operators could be injected but you should always properly validate and sanitize user input.</p><p>For backward compatibility reasons Sequelize sets the following aliases by default -
1839$eq, $ne, $gte, $gt, $lte, $lt, $not, $in, $notIn, $is, $like, $notLike, $iLike, $notILike, $regexp, $notRegexp, $iRegexp, $notIRegexp, $between, $notBetween, $overlap, $contains, $contained, $adjacent, $strictLeft, $strictRight, $noExtendRight, $noExtendLeft, $and, $or, $any, $all, $values, $col</p><p>Currently the following legacy aliases are also set but are planned to be fully removed in the near future - 1840ne, not, in, notIn, gte, gt, lte, lt, like, ilike, $ilike, nlike, $notlike, notilike, .., between, !.., notbetween, nbetween, overlap, &&, @>, <@</p><p>For better security it is highly advised to use <code>Sequelize.Op</code> and not depend on any string alias at all. You can limit alias your application will need by setting <code>operatorsAliases</code> option, remember to sanitize user input especially when you are directly passing them to Sequelize methods.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op; 1841 1842//use sequelize without any operators aliases 1843const connection = new Sequelize(db, user, pass, { operatorsAliases: false }); 1844 1845//use sequelize with only alias for $and => Op.and 1846const connection2 = new Sequelize(db, user, pass, { operatorsAliases: { $and: Op.and } });</code> 1847</code></pre><p>Sequelize will warn you if you're using the default aliases and not limiting them 1848if you want to keep using all default aliases (excluding legacy ones) without the warning you can pass the following operatorsAliases option -</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op; 1849const operatorsAliases = { 1850 $eq: Op.eq, 1851 $ne: Op.ne, 1852 $gte: Op.gte, 1853 $gt: Op.gt, 1854 $lte: Op.lte, 1855 $lt: Op.lt, 1856 $not: Op.not, 1857 $in: Op.in, 1858 $notIn: Op.notIn, 1859 $is: Op.is, 1860 $like: Op.like, 1861 $notLike: Op.notLike, 1862 $iLike: Op.iLike, 1863 $notILike: Op.notILike, 1864 $regexp: Op.regexp, 1865 $notRegexp: Op.notRegexp, 1866 $iRegexp: Op.iRegexp, 1867 $notIRegexp: Op.notIRegexp, 1868 $between: Op.between, 1869 $notBetween: Op.notBetween, 1870 $overlap: Op.overlap, 1871 $contains: Op.contains, 1872 $contained: Op.contained, 1873 $adjacent: Op.adjacent, 1874 $strictLeft: Op.strictLeft, 1875 $strictRight: Op.strictRight, 1876 $noExtendRight: Op.noExtendRight, 1877 $noExtendLeft: Op.noExtendLeft, 1878 $and: Op.and, 1879 $or: Op.or, 1880 $any: Op.any, 1881 $all: Op.all, 1882 $values: Op.values, 1883 $col: Op.col 1884}; 1885 1886const connection = new Sequelize(db, user, pass, { operatorsAliases });</code> 1887</code></pre><h3>JSON</h3><p>The JSON data type is supported by the PostgreSQL, SQLite and MySQL dialects only. </p><h4>PostgreSQL</h4><p>The JSON data type in PostgreSQL stores the value as plain text, as opposed to binary representation. If you simply want to store and retrieve a JSON representation, using JSON will take less disk space and less time to build from its input representation. However, if you want to do any operations on the JSON value, you should prefer the JSONB data type described below.</p><h4>MSSQL</h4><p>MSSQL does not have a JSON data type, however it does provide support for JSON stored as strings through certain functions since SQL Server 2016. Using these functions, you will be able to query the JSON stored in the string, but any returned values will need to be parsed separately. </p><pre><code class="lang-js"><code class="source-code prettyprint">// ISJSON - to test if a string contains valid JSON 1888User.findAll({ 1889 where: sequelize.where(sequelize.fn('ISJSON', sequelize.col('userDetails')), 1) 1890}) 1891 1892// JSON_VALUE - extract a scalar value from a JSON string 1893User.findAll({ 1894 attributes: [[ sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), 'address line 1']] 1895}) 1896 1897// JSON_VALUE - query a scalar value from a JSON string 1898User.findAll({ 1899 where: sequelize.where(sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), '14, Foo Street') 1900}) 1901 1902// JSON_QUERY - extract an object or array 1903User.findAll({ 1904 attributes: [[ sequelize.fn('JSON_QUERY', sequelize.col('userDetails'), '$.address'), 'full address']] 1905})</code> 1906</code></pre><h3>JSONB</h3><p>JSONB can be queried in three different ways.</p><h4>Nested object</h4><pre><code class="lang-js"><code class="source-code prettyprint">{ 1907 meta: { 1908 video: { 1909 url: { 1910 [Op.ne]: null 1911 } 1912 } 1913 } 1914}</code> 1915</code></pre><h4>Nested key</h4><pre><code class="lang-js"><code class="source-code prettyprint">{ 1916 "meta.audio.length": { 1917 [Op.gt]: 20 1918 } 1919}</code> 1920</code></pre><h4>Containment</h4><pre><code class="lang-js"><code class="source-code prettyprint">{ 1921 "meta": { 1922 [Op.contains]: { 1923 site: { 1924 url: 'http://google.com' 1925 } 1926 } 1927 } 1928}</code> 1929</code></pre><h3>Relations / Associations</h3><pre><code class="lang-js"><code class="source-code prettyprint">// Find all projects with a least one task where task.state === project.state 1930Project.findAll({ 1931 include: [{ 1932 model: Task, 1933 where: { state: Sequelize.col('project.state') } 1934 }] 1935})</code> 1936</code></pre><h2>Pagination / Limiting</h2><pre><code class="lang-js"><code class="source-code prettyprint">// Fetch 10 instances/rows 1937Project.findAll({ limit: 10 }) 1938 1939// Skip 8 instances/rows 1940Project.findAll({ offset: 8 }) 1941 1942// Skip 5 instances and fetch the 5 after that 1943Project.findAll({ offset: 5, limit: 5 })</code> 1944</code></pre><h2>Ordering</h2><p><code>order</code> takes an array of items to order the query by or a sequelize method. Generally you will want to use a tuple/array of either attribute, direction or just direction to ensure proper escaping.</p><pre><code class="lang-js"><code class="source-code prettyprint">Subtask.findAll({ 1945 order: [ 1946 // Will escape title and validate DESC against a list of valid direction parameters 1947 ['title', 'DESC'], 1948 1949 // Will order by max(age) 1950 sequelize.fn('max', sequelize.col('age')), 1951 1952 // Will order by max(age) DESC 1953 [sequelize.fn('max', sequelize.col('age')), 'DESC'], 1954 1955 // Will order by otherfunction(`col1`, 12, 'lalala') DESC 1956 [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'], 1957 1958 // Will order an associated model's created_at using the model name as the association's name. 1959 [Task, 'createdAt', 'DESC'], 1960 1961 // Will order through an associated model's created_at using the model names as the associations' names. 1962 [Task, Project, 'createdAt', 'DESC'], 1963 1964 // Will order by an associated model's created_at using the name of the association. 1965 ['Task', 'createdAt', 'DESC'], 1966 1967 // Will order by a nested associated model's created_at using the names of the associations. 1968 ['Task', 'Project', 'createdAt', 'DESC'], 1969 1970 // Will order by an associated model's created_at using an association object. (preferred method) 1971 [Subtask.associations.Task, 'createdAt', 'DESC'], 1972 1973 // Will order by a nested associated model's created_at using association objects. (preferred method) 1974 [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'], 1975 1976 // Will order by an associated model's created_at using a simple association object. 1977 [{model: Task, as: 'Task'}, 'createdAt', 'DESC'], 1978 1979 // Will order by a nested associated model's created_at simple association objects. 1980 [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC'] 1981 ] 1982 1983 // Will order by max age descending 1984 order: sequelize.literal('max(age) DESC') 1985 1986 // Will order by max age ascending assuming ascending is the default order when direction is omitted 1987 order: sequelize.fn('max', sequelize.col('age')) 1988 1989 // Will order by age ascending assuming ascending is the default order when direction is omitted 1990 order: sequelize.col('age') 1991 1992 // Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM')) 1993 order: sequelize.random() 1994})</code> 1995</code></pre><h2>Table Hint</h2><p><code>tableHint</code> can be used to optionally pass a table hint when using mssql. The hint must be a value from <code>Sequelize.TableHints</code> and should only be used when absolutely necessary. Only a single table hint is currently supported per query. </p><p>Table hints override the default behavior of mssql query optimizer by specifying certain options. They only affect the table or view referenced in that clause.</p><pre><code class="lang-js"><code class="source-code prettyprint">const TableHints = Sequelize.TableHints; 1996 1997Project.findAll({ 1998 // adding the table hint NOLOCK 1999 tableHint: TableHints.NOLOCK 2000 // this will generate the SQL 'WITH (NOLOCK)' 2001})</code> 2002</code></pre></div> 2003 <a data-ice='link' href='/v4/manual/tutorial/querying'></a> 2004 </div> 2005 </div> 2006<div class="manual-card-wrap" data-ice="cards"> 2007 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â "><span data-ice="label-inner">Instances</span></h1> 2008 <div class="manual-card"> 2009 <div data-ice="card"><h1>Instances</h1><h2>Building a non-persistent instance</h2><p>In order to create instances of defined classes just do as follows. You might recognize the syntax if you coded Ruby in the past. Using the <code>build</code>-method will return an unsaved object, which you explicitly have to save.</p><pre><code class="lang-js"><code class="source-code prettyprint">const project = Project.build({ 2010 title: 'my awesome project', 2011 description: 'woot woot. this will make me a rich man' 2012}) 2013 2014const task = Task.build({ 2015 title: 'specify the project idea', 2016 description: 'bla', 2017 deadline: new Date() 2018})</code> 2019</code></pre><p>Built instances will automatically get default values when they were defined:</p><pre><code class="lang-js"><code class="source-code prettyprint">// first define the model 2020const Task = sequelize.define('task', { 2021 title: Sequelize.STRING, 2022 rating: { type: Sequelize.STRING, defaultValue: 3 } 2023}) 2024 2025// now instantiate an object 2026const task = Task.build({title: 'very important task'}) 2027 2028task.title // ==> 'very important task' 2029task.rating // ==> 3</code> 2030</code></pre><p>To get it stored in the database, use the <code>save</code>-method and catch the events ... if needed:</p><pre><code class="lang-js"><code class="source-code prettyprint">project.save().then(() => { 2031 // my nice callback stuff 2032}) 2033 2034task.save().catch(error => { 2035 // mhhh, wth! 2036}) 2037 2038// you can also build, save and access the object with chaining: 2039Task 2040 .build({ title: 'foo', description: 'bar', deadline: new Date() }) 2041 .save() 2042 .then(anotherTask => { 2043 // you can now access the currently saved task with the variable anotherTask... nice! 2044 }) 2045 .catch(error => { 2046 // Ooops, do some error-handling 2047 })</code> 2048</code></pre><h2>Creating persistent instances</h2><p>While an instance created with <code>.build()</code> requires an explicit <code>.save()</code> call to be stored in the database, <code>.create()</code> omits that requirement altogether and automatically stores your instance's data once called.</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => { 2049 // you can now access the newly created task via the variable task 2050})</code> 2051</code></pre><p>It is also possible to define which attributes can be set via the create method. This can be especially very handy if you create database entries based on a form which can be filled by a user. Using that would for example allow you to restrict the <code>User</code> model to set only a username and an address but not an admin flag:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => { 2052 // let's assume the default of isAdmin is false: 2053 console.log(user.get({ 2054 plain: true 2055 })) // => { username: 'barfooz', isAdmin: false } 2056})</code> 2057</code></pre><h2>Updating / Saving / Persisting an instance</h2><p>Now lets change some values and save changes to the database... There are two ways to do that:</p><pre><code class="lang-js"><code class="source-code prettyprint">// way 1 2058task.title = 'a very different title now' 2059task.save().then(() => {}) 2060 2061// way 2 2062task.update({ 2063 title: 'a very different title now' 2064}).then(() => {})</code> 2065</code></pre><p>It's also possible to define which attributes should be saved when calling <code>save</code>, by passing an array of column names. This is useful when you set attributes based on a previously defined object. E.g. if you get the values of an object via a form of a web app. Furthermore this is used internally for <code>update</code>. This is how it looks like:</p><pre><code class="lang-js"><code class="source-code prettyprint">task.title = 'foooo' 2066task.description = 'baaaaaar' 2067task.save({fields: ['title']}).then(() => { 2068 // title will now be 'foooo' but description is the very same as before 2069}) 2070 2071// The equivalent call using update looks like this: 2072task.update({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(() => { 2073 // title will now be 'foooo' but description is the very same as before 2074})</code> 2075</code></pre><p>When you call <code>save</code> without changing any attribute, this method will execute nothing;</p><h2>Destroying / Deleting persistent instances</h2><p>Once you created an object and got a reference to it, you can delete it from the database. The relevant method is <code>destroy</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.create({ title: 'a task' }).then(task => { 2076 // now you see me... 2077 return task.destroy(); 2078}).then(() => { 2079 // now i'm gone :) 2080})</code> 2081</code></pre><p>If the <code>paranoid</code> options is true, the object will not be deleted, instead the <code>deletedAt</code> column will be set to the current timestamp. To force the deletion, you can pass <code>
2081force: true</code> to the destroy call:</p><pre><code class="lang-js"><code class="source-code prettyprint">task.destroy({ force: true })</code> 2082</code></pre><h2>Working in bulk (creating, updating and destroying multiple rows at once)</h2><p>In addition to updating a single instance, you can also create, update, and delete multiple instances at once. The functions you are looking for are called</p><ul> 2083<li><code>Model.bulkCreate</code></li> 2084<li><code>Model.update</code></li> 2085<li><code>Model.destroy</code></li> 2086</ul><p>Since you are working with multiple models, the callbacks will not return DAO instances. BulkCreate will return an array of model instances/DAOs, they will however, unlike <code>create</code>, not have the resulting values of autoIncrement attributes.<code>update</code> and <code>destroy</code> will return the number of affected rows.</p><p>First lets look at bulkCreate</p><pre><code class="lang-js"><code class="source-code prettyprint">User.bulkCreate([ 2087 { username: 'barfooz', isAdmin: true }, 2088 { username: 'foo', isAdmin: true }, 2089 { username: 'bar', isAdmin: false } 2090]).then(() => { // Notice: There are no arguments here, as of right now you'll have to... 2091 return User.findAll(); 2092}).then(users => { 2093 console.log(users) // ... in order to get the array of user objects 2094})</code> 2095</code></pre><p>To update several rows at once:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.bulkCreate([ 2096 {subject: 'programming', status: 'executing'}, 2097 {subject: 'reading', status: 'executing'}, 2098 {subject: 'programming', status: 'finished'} 2099]).then(() => { 2100 return Task.update( 2101 { status: 'inactive' }, /* set attributes' value */ 2102 { where: { subject: 'programming' }} /* where criteria */ 2103 ); 2104}).spread((affectedCount, affectedRows) => { 2105 // .update returns two values in an array, therefore we use .spread 2106 // Notice that affectedRows will only be defined in dialects which support returning: true 2107 2108 // affectedCount will be 2 2109 return Task.findAll(); 2110}).then(tasks => { 2111 console.log(tasks) // the 'programming' tasks will both have a status of 'inactive' 2112})</code> 2113</code></pre><p>And delete them:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.bulkCreate([ 2114 {subject: 'programming', status: 'executing'}, 2115 {subject: 'reading', status: 'executing'}, 2116 {subject: 'programming', status: 'finished'} 2117]).then(() => { 2118 return Task.destroy({ 2119 where: { 2120 subject: 'programming' 2121 }, 2122 truncate: true /* this will ignore where and truncate the table instead */ 2123 }); 2124}).then(affectedRows => { 2125 // affectedRows will be 2 2126 return Task.findAll(); 2127}).then(tasks => { 2128 console.log(tasks) // no programming, just reading :( 2129})</code> 2130</code></pre><p>If you are accepting values directly from the user, it might be beneficial to limit the columns that you want to actually insert.<code>bulkCreate()</code>accepts an options object as the second parameter. The object can have a <code>fields</code> parameter, (an array) to let it know which fields you want to build explicitly</p><pre><code class="lang-js"><code class="source-code prettyprint">User.bulkCreate([ 2131 { username: 'foo' }, 2132 { username: 'bar', admin: true} 2133], { fields: ['username'] }).then(() => { 2134 // nope bar, you can't be admin! 2135})</code> 2136</code></pre><p><code>bulkCreate</code> was originally made to be a mainstream/fast way of inserting records, however, sometimes you want the luxury of being able to insert multiple rows at once without sacrificing model validations even when you explicitly tell Sequelize which columns to sift through. You can do by adding a <code>validate: true</code> property to the options object.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Tasks = sequelize.define('task', { 2137 name: { 2138 type: Sequelize.STRING, 2139 validate: { 2140 notNull: { args: true, msg: 'name cannot be null' } 2141 } 2142 }, 2143 code: { 2144 type: Sequelize.STRING, 2145 validate: { 2146 len: [3, 10] 2147 } 2148 } 2149}) 2150 2151Tasks.bulkCreate([ 2152 {name: 'foo', code: '123'}, 2153 {code: '1234'},
2154 {name: 'bar', code: '1'} 2155], { validate: true }).catch(errors => { 2156 /* console.log(errors) would look like: 2157 [ 2158 { record: 2159 ... 2160 name: 'SequelizeBulkRecordError', 2161 message: 'Validation error', 2162 errors: 2163 { name: 'SequelizeValidationError', 2164 message: 'Validation error', 2165 errors: [Object] } }, 2166 { record: 2167 ... 2168 name: 'SequelizeBulkRecordError', 2169 message: 'Validation error', 2170 errors: 2171 { name: 'SequelizeValidationError', 2172 message: 'Validation error', 2173 errors: [Object] } } 2174 ] 2175 */ 2176})</code> 2177</code></pre><h2>Values of an instance</h2><p>If you log an instance you will notice, that there is a lot of additional stuff. In order to hide such stuff and reduce it to the very interesting information, you can use the<code>get</code>-attribute. Calling it with the option <code>plain</code> = true will only return the values of an instance.</p><pre><code class="lang-js"><code class="source-code prettyprint">Person.create({ 2178 name: 'Rambow', 2179 firstname: 'John' 2180}).then(john => { 2181 console.log(john.get({ 2182 plain: true 2183 })) 2184}) 2185 2186// result: 2187 2188// { name: 'Rambow', 2189// firstname: 'John', 2190// id: 1, 2191// createdAt: Tue, 01 May 2012 19:12:16 GMT, 2192// updatedAt: Tue, 01 May 2012 19:12:16 GMT 2193// }</code> 2194</code></pre><p><strong>Hint:</strong>You can also transform an instance into JSON by using <code>JSON.stringify(instance)</code>. This will basically return the very same as <code>values</code>.</p><h2>Reloading instances</h2><p>If you need to get your instance in sync, you can use the method<code>reload</code>. It will fetch the current data from the database and overwrite the attributes of the model on which the method has been called on.</p><pre><code class="lang-js"><code class="source-code prettyprint">Person.findOne({ where: { name: 'john' } }).then(person => { 2195 person.name = 'jane' 2196 console.log(person.name) // 'jane' 2197 2198 person.reload().then(() => { 2199 console.log(person.name) // 'john' 2200 }) 2201})</code> 2202</code></pre><h2>Incrementing</h2><p>In order to increment values of an instance without running into concurrency issues, you may use <code>increment</code>.</p><p>First of all you can define a field and the value you want to add to it.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findById(1).then(user => { 2203 return user.increment('my-integer-field', {by: 2}) 2204}).then(user => { 2205 // Postgres will return the updated user by default (unless disabled by setting { returning: false }) 2206 // In other dialects, you'll want to call user.reload() to get the updated instance... 2207})</code> 2208</code></pre><p>Second, you can define multiple fields and the value you want to add to them.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findById(1).then(user => { 2209 return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2}) 2210}).then(/* ... */)</code> 2211</code></pre><p>Third, you can define an object containing fields and its increment values.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findById(1).then(user => { 2212 return user.increment({ 2213 'my-integer-field': 2, 2214 'my-very-other-field': 3 2215 }) 2216}).then(/* ... */)</code> 2217</code></pre><h2>Decrementing</h2><p>In order to decrement values of an instance without running into concurrency issues, you may use <code>decrement</code>.</p><p>First of all you can define a field and the value you want to add to it.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findById(1).then(user => { 2218 return user.decrement('my-integer-field', {by: 2}) 2219}).then(user => { 2220 // Postgres will return the updated user by default (unless disabled by setting { returning: false }) 2221 // In other dialects, you'll want to call user.reload() to get the updated instance... 2222})</code> 2223</code></pre><p>Second, you can define multiple fields and the value you want to add to them.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findById(1).then(user => { 2224 return user.decrement([ 'my-integer-field', 'my-very-other-field' ], {by: 2}) 2225}).then(/* ... */)</code> 2226</code></pre><p>
2226Third, you can define an object containing fields and its decrement values.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findById(1).then(user => { 2227 return user.decrement({ 2228 'my-integer-field': 2, 2229 'my-very-other-field': 3 2230 }) 2231}).then(/* ... */)</code> 2232</code></pre></div> 2233 <a data-ice='link' href='/v4/manual/tutorial/instances'></a> 2234 </div> 2235 </div> 2236<div class="manual-card-wrap" data-ice="cards"> 2237 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â â â "><span data-ice="label-inner">Associations</span></h1> 2238 <div class="manual-card"> 2239 <div data-ice="card"><h1>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>One-To-One associations</h2><p>One-To-One associations are associations between exactly two models connected by a single foreign key.</p><h3>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">const Player = this.sequelize.define('player', {/* attributes */}); 2240const Team = this.sequelize.define('team', {/* attributes */}); 2241 2242Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team</code> 2243</code></pre><h4>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">const User = this.sequelize.define('user', {/* attributes */}) 2244const Company = this.sequelize.define('company', {/* attributes */}); 2245 2246User.belongsTo(Company); // Will add companyId to user 2247 2248const User = this.sequelize.define('user', {/* attributes */}, {underscored: true}) 2249const Company = this.sequelize.define('company', { 2250 uuid: { 2251 type: Sequelize.UUID, 2252 primaryKey: true 2253 } 2254}); 2255 2256User.belongsTo(Company); // Will add company_uuid to user</code> 2257</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">const User = this.sequelize.define('user', {/* attributes */}) 2258const UserRole = this.sequelize.define('userRole', {/* attributes */}); 2259 2260User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId</code> 2261</code></pre><p>In all cases the default foreign key can be overwritten with the <code>foreignKey</code> option. 2262When the foreign key option is used, Sequelize will use it as-is:</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = this.sequelize.define('user', {/* attributes */}) 2263const Company = this.sequelize.define('company', {/* attributes */}); 2264 2265User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User</code> 2266</code></pre><h4>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'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">const User = this.sequelize.define('user', {/* attributes */}) 2267const Company = this.sequelize.define('company', {/* attributes */}); 2268 2269User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User</code> 2270</code></pre><h3>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">const User = sequelize.define('user', {/* ... */}) 2271const Project = sequelize.define('project', {/* ... */}) 2272 2273// One-way associations 2274Project.hasOne(User) 2275 2276/* 2277 In this example hasOne will add an attribute projectId to the User model! 2278 Furthermore, Project.prototype will gain the methods getUser and setUser according 2279 to the first parameter passed to define. If you have underscore style 2280 enabled, the added attribute will be project_id instead of projectId. 2281 2282 The foreign key will be placed on the users table. 2283 2284 You can also define the foreign key, e.g. if you already have an existing 2285 database and want to work on it: 2286*/ 2287 2288Project.hasOne(User, { foreignKey: 'initiator_id' }) 2289 2290/* 2291 Because Sequelize will use the model's name (first parameter of define) for 2292 the accessor methods, it is also possible to pass a special option to hasOne: 2293*/ 2294 2295Project.hasOne(User, { as: 'Initiator' }) 2296// Now you will get Project.getInitiator and Project.setInitiator 2297 2298// Or let's define some self references 2299const Person = sequelize.define('person', { /* ... */}) 2300 2301Person.hasOne(Person, {as: 'Father'}) 2302// this will add the attribute FatherId to Person 2303 2304// also possible: 2305Person.hasOne(Person, {as: 'Father', foreignKey: 'DadId'}) 2306// this will add the attribute DadId to Person 2307 2308// In both cases you will be able to do: 2309Person.setFather 2310Person.getFather 2311 2312// If you need to join a table twice you can double join the same table 2313Team.hasOne(Game, {as: 'HomeTeam', foreignKey : 'homeTeamId'}); 2314Team.hasOne(Game, {as: 'AwayTeam', foreignKey : 'awayTeamId'}); 2315 2316Game.belongsTo(Team);</code> 2317</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>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">const Player = this.sequelize.define('player', {/* attributes */}) 2318const Team = this.sequelize.define('team', {/* attributes */});</code> 2319</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); 2320//Or 2321Player.hasOne(Team);</code> 2322</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); 2323//Or 2324Team.hasOne(Player);</code> 2325</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">const Player = this.sequelize.define('player', {/* attributes */}) 2326const Coach = this.sequelize.define('coach', {/* attributes */}) 2327const Team = this.sequelize.define('team', {/* attributes */});</code> 2328</code></pre><p>Suppose our <code>Player</code> model has information about its team as <code>teamId</code> column. Information about each Team'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> 2329</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> 2330</code></pre><h2>One-To-Many associations (hasMany)</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">const User = sequelize.define('user', {/* ... */}) 2331const Project = sequelize.define('project', {/* ... */}) 2332 2333// OK. Now things get more complicated (not really visible to the user :)). 2334// First let's define a hasMany association 2335Project.hasMany(User, {as: 'Workers'})</code> 2336</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>. </p><p>
2336Sometimes 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">const City = sequelize.define('city', { countryCode: Sequelize.STRING }); 2337const Country = sequelize.define('country', { isoCode: Sequelize.STRING }); 2338 2339// Here we can connect countries and cities base on country code 2340Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'}); 2341City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});</code> 2342</code></pre><p>So far we dealt with a one-way association. But we want more! Let's define it the other way around by creating a many to many association in the next section.</p><h2>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: 'UserProject'}); 2343User.belongsToMany(Project, {through: 'UserProject'});</code> 2344</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'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: 'Tasks', through: 'worker_tasks', foreignKey: 'userId' }) 2345Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId' })</code> 2346</code></pre><p><code>foreignKey</code> will allow you to set <strong>source model</strong> key in the <strong>through</strong> relation. 2347<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: 'Tasks', through: 'worker_tasks', foreignKey: 'userId', otherKey: 'projectId'})</code> 2348</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: 'Children', through: 'PersonChildren' }) 2349// This will create the table PersonChildren which stores the ids of the objects.</code> 2350</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">const User = sequelize.define('user', {}) 2351const Project = sequelize.define('project', {}) 2352const UserProjects = sequelize.define('userProjects', { 2353 status: DataTypes.STRING 2354}) 2355 2356User.belongsToMany(Project, { through: UserProjects }) 2357Project.belongsToMany(User, { through: UserProjects })</code> 2358</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: 'started' }})</code> 2359</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">const UserProjects = sequelize.define('userProjects', { 2360 id: { 2361 type: Sequelize.INTEGER, 2362 primaryKey: true, 2363 autoIncrement: true 2364 }, 2365 status: DataTypes.STRING 2366})</code> 2367</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({ 2368 include: [{ 2369 model: Project, 2370 through: { 2371 attributes: ['createdAt', 'startedAt', 'finishedAt'], 2372 where: {completed: true} 2373 } 2374 }] 2375});</code> 2376</code></pre><p>Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using <strong>uniqueKey</strong> option.</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.belongsToMany(User, { through: UserProjects, uniqueKey: 'my_custom_unique' })</code> 2377</code></pre><h2>Scopes</h2><p>This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see <a href='/v4/manual/tutorial/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>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">const Comment = this.sequelize.define('comment', { 2378 title: Sequelize.STRING, 2379 commentable: Sequelize.STRING, 2380 commentable_id: Sequelize.INTEGER 2381}); 2382 2383Comment.prototype.getItem = function(options) { 2384 return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)](options); 2385}; 2386 2387Post.hasMany(this.Comment, { 2388 foreignKey: 'commentable_id', 2389 constraints: false, 2390 scope: { 2391 commentable: 'post' 2392 } 2393}); 2394Comment.belongsTo(this.Post, { 2395 foreignKey: 'commentable_id', 2396 constraints: false, 2397 as: 'post' 2398}); 2399 2400Image.hasMany(this.Comment, { 2401 foreignKey: 'commentable_id', 2402 constraints: false, 2403 scope: { 2404 commentable: 'image' 2405 } 2406}); 2407Comment.belongsTo(this.Image, { 2408 foreignKey: 'commentable_id', 2409 constraints: false, 2410 as: 'image' 2411});</code> 2412</code></pre><p><code>constraints: false,</code> disables references constraints - since the <code>commentable_id</code> column references several tables, we cannot add a <code>REFERENCES</code> constraint to it. Note that the Image -> Comment and Post -> Comment relations define a scope, <code>commentable: 'image'</code> and <code>commentable: 'post'</code> respectively. This scope is automatically applied when using the association functions:</p><pre><code class="lang-js"><code class="source-code prettyprint">image.getComments() 2413SELECT * FROM comments WHERE commentable_id = 42 AND commentable = 'image'; 2414 2415image.createComment({ 2416 title: 'Awesome!' 2417}) 2418INSERT INTO comments (title, commentable_id, commentable) VALUES ('Awesome!', 42, 'image'); 2419 2420image.addComment(comment); 2421UPDATE comments SET commentable_id = 42, commentable = 'image'</code> 2422</code></pre><p>The <code>getItem</code> utility function on <code>Comment</code> completes the picture - it simply converts the <code>commentable</code> string into a call to either <code>getImage</code> or <code>getPost</code>, providing an abstraction over whether a comment belongs to a post or an image. You can pass a normal options object as a parameter to <code>getItem(options)</code> to specify any where conditions or includes.</p><h4>n:m</h4><p>Continuing with the idea of a polymorphic model, consider a tag table - an item can have multiple tags, and a tag can be related to several items.</p><p>For brevity, the example only shows a Post model, but in reality Tag would be related to several other models.</p><pre><code class="lang-js"><code class="source-code prettyprint">const ItemTag = sequelize.define('item_tag', { 2423 id : { 2424 type: DataTypes.INTEGER, 2425 primaryKey: true, 2426 autoIncrement: true 2427 }, 2428 tag_id: { 2429 type: DataTypes.INTEGER, 2430 unique: 'item_tag_taggable' 2431 }, 2432 taggable: { 2433 type: DataTypes.STRING, 2434 unique: 'item_tag_taggable' 2435 }, 2436 taggable_id: { 2437 type: DataTypes.INTEGER, 2438 unique: 'item_tag_taggable', 2439 references: null 2440 } 2441}); 2442const Tag = sequelize.define('tag', { 2443 name: DataTypes.STRING 2444}); 2445 2446Post.belongsToMany(Tag, { 2447 through: { 2448 model: ItemTag, 2449 unique: false, 2450 scope: { 2451 taggable: 'post' 2452 } 2453 }, 2454 foreignKey: 'taggable_id', 2455 constraints: false 2456}); 2457Tag.belongsToMany(Post, { 2458 through: { 2459 model: ItemTag, 2460 unique: false 2461 }, 2462 foreignKey: 'tag_id', 2463 constraints: false 2464});</code> 2465</code></pre><p>Notice that the scoped column (<code>taggable</code>) is now on the through model (<code>ItemTag</code>).</p><p>We could also define a more restrictive association, for example, to get all pending tags for a post by applying a scope of both the through model (<code>ItemTag</code>) and the target model (<code>Tag</code>):</p><pre><code class="lang-js"><code class="source-code prettyprint">Post.hasMany(Tag, { 2466 through: { 2467 model: ItemTag, 2468 unique: false, 2469 scope: { 2470 taggable: 'post' 2471 } 2472 }, 2473 scope: { 2474 status: 'pending' 2475 }, 2476 as: 'pendingTags', 2477 foreignKey: 'taggable_id', 2478 constraints: false 2479}); 2480 2481Post.getPendingTags();</code> 2482</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT `tag`.* INNER JOIN `item_tags` AS `item_tag` 2483ON `tag`.`id` = `item_tag`.`tagId` 2484 AND `item_tag`.`taggable_id` = 42 2485 AND `item_tag`.`taggable` = 'post' 2486WHERE (`tag`.`status` = 'pending');</code> 2487</code></pre><p><code>constraints: false</code> disables references constraints on the <code>taggable_id</code> column. Because the column is polymorphic, we cannot say that it <code>REFERENCES</code> a specific table.</p><h2>Naming strategy</h2><p>By default sequelize will use the model name (the name passed to <code>sequelize.define</code>) to figure out the name of the model when used in associations. For example, a model named <code>user</code> will add the functions <code>get/set/add User</code> to instances of the associated model, and a property named <code>.user</code> in eager loading, while a model named <code>User</code> will add the same functions, but a property named <code>.User</code> (notice the upper case U) in eager loading.</p><p>As we've already seen, you can alias models in associations using <code>as</code>. In single associations (has one and belongs to), the alias should be singular, while for many associations (has many) it should be plural. Sequelize then uses the <a href="https://www.npmjs.org/package/inflection">inflection </a>library to convert the alias to its singular form. However, this might not always work for irregular or non-english words. In this case, you can provide both the plural and the singular form of the alias:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.belongsToMany(Project, { as: { singular: 'task', plural: 'tasks' }}
2487) 2488// Notice that inflection has no problem singularizing tasks, this is just for illustrative purposes.</code> 2489</code></pre><p>If you know that a model will always use the same alias in associations, you can provide it when creating the model</p><pre><code class="lang-js"><code class="source-code prettyprint">const Project = sequelize.define('project', attributes, { 2490 name: { 2491 singular: 'task', 2492 plural: 'tasks', 2493 } 2494}) 2495 2496User.belongsToMany(Project);</code> 2497</code></pre><p>This will add the functions <code>add/set/get Tasks</code> to user instances.</p><p>Remember, that using <code>as</code> to change the name of the association will also change the name of the foreign key. When using <code>as</code>, it is safest to also specify the foreign key.</p><pre><code class="lang-js"><code class="source-code prettyprint">Invoice.belongsTo(Subscription) 2498Subscription.hasMany(Invoice)</code> 2499</code></pre><p>Without <code>as</code>, this adds <code>subscriptionId</code> as expected. However, if you were to say <code>Invoice.belongsTo(Subscription, { as: 'TheSubscription' })</code>, you will have both <code>subscriptionId</code> and <code>theSubscriptionId</code>, because sequelize is not smart enough to figure that the calls are two sides of the same relation. 'foreignKey' fixes this problem;</p><pre><code class="lang-js"><code class="source-code prettyprint">Invoice.belongsTo(Subscription, , { as: 'TheSubscription', foreignKey: 'subscription_id' }) 2500Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' )</code> 2501</code></pre><h2>Associating objects</h2><p>Because Sequelize is doing a lot of magic, you have to call <code>Sequelize.sync</code> after setting the associations! Doing so will allow you the following:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.hasMany(Task) 2502Task.belongsTo(Project) 2503 2504Project.create()... 2505Task.create()... 2506Task.create()... 2507 2508// save them... and then: 2509project.setTasks([task1, task2]).then(() => { 2510 // saved! 2511}) 2512 2513// ok, now they are saved... how do I get them later on? 2514project.getTasks().then(associatedTasks => { 2515 // associatedTasks is an array of tasks 2516}) 2517 2518// You can also pass filters to the getter method. 2519// They are equal to the options you can pass to a usual finder method. 2520project.getTasks({ where: 'id > 10' }).then(tasks => { 2521 // tasks with an id greater than 10 :) 2522}) 2523 2524// You can also only retrieve certain fields of a associated object. 2525project.getTasks({attributes: ['title']}).then(tasks => { 2526 // retrieve tasks with the attributes "title" and "id" 2527})</code> 2528</code></pre><p>To remove created associations you can just call the set method without a specific id:</p><pre><code class="lang-js"><code class="source-code prettyprint">// remove the association with task1 2529project.setTasks([task2]).then(associatedTasks => { 2530 // you will get task2 only 2531}) 2532 2533// remove 'em all 2534project.setTasks([]).then(associatedTasks => { 2535 // you will get an empty array 2536}) 2537 2538// or remove 'em more directly 2539project.removeTask(task1).then(() => { 2540 // it's gone 2541}) 2542 2543// and add 'em again 2544project.addTask(task1).then(function() { 2545 // it's back again 2546})</code> 2547</code></pre><p>You can of course also do it vice versa:</p><pre><code class="lang-js"><code class="source-code prettyprint">// project is associated with task1 and task2 2548task2.setProject(null).then(function() { 2549 // and it's gone 2550})</code> 2551</code></pre><p>For hasOne/belongsTo it's basically the same:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.hasOne(User, {as: "Author"}) 2552Task.setAuthor(anAuthor)</code> 2553</code></pre><p>Adding associations to a relation with a custom join table can be done in two ways (continuing with the associations defined in the previous chapter):</p><pre><code class="lang-js"><code class="source-code prettyprint">// Either by adding a property with the name of the join table model to the object, before creating the association 2554project.UserProjects = { 2555 status: 'active' 2556} 2557u.addProject(project) 2558 2559// Or by providing a second options.through argument when adding the association, containing the data that should go in the join table 2560u.addProject(project, { through: { status: 'active' }}) 2561 2562 2563// When associating multiple objects, you can combine the two options above. In this case the second argument 2564// will be treated as a defaults object, that will be used if no data is provided 2565project1.UserProjects = { 2566 status: 'inactive' 2567} 2568 2569u.setProjects([project1, project2], { through: { status: 'active' }})
2570// The code above will record inactive for project one, and active for project two in the join table</code> 2571</code></pre><p>When getting data on an association that has a custom join table, the data from the join table will be returned as a DAO instance:</p><pre><code class="lang-js"><code class="source-code prettyprint">u.getProjects().then(projects => { 2572 const project = projects[0] 2573 2574 if (project.UserProjects.status === 'active') { 2575 // .. do magic 2576 2577 // since this is a real DAO instance, you can save it directly after you are done doing magic 2578 return project.UserProjects.save() 2579 } 2580})</code> 2581</code></pre><p>If you only need some of the attributes from the join table, you can provide an array with the attributes you want:</p><pre><code class="lang-js"><code class="source-code prettyprint">// This will select only name from the Projects table, and only status from the UserProjects table 2582user.getProjects({ attributes: ['name'], joinTableAttributes: ['status']})</code> 2583</code></pre><h2>Check associations</h2><p>You can also check if an object is already associated with another one (N:M only). Here is how you'd do it:</p><pre><code class="lang-js"><code class="source-code prettyprint">// check if an object is one of associated ones: 2584Project.create({ /* */ }).then(project => { 2585 return User.create({ /* */ }).then(user => { 2586 return project.hasUser(user).then(result => { 2587 // result would be false 2588 return project.addUser(user).then(() => { 2589 return project.hasUser(user).then(result => { 2590 // result would be true 2591 }) 2592 }) 2593 }) 2594 }) 2595}) 2596 2597// check if all associated objects are as expected: 2598// let's assume we have already a project and two users 2599project.setUsers([user1, user2]).then(() => { 2600 return project.hasUsers([user1]); 2601}).then(result => { 2602 // result would be true 2603 return project.hasUsers([user1, user2]); 2604}).then(result => { 2605 // result would be true 2606})</code> 2607</code></pre><h2>Foreign Keys</h2><p>When you create associations between your models in sequelize, foreign key references with constraints will automatically be created. The setup below:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Task = this.sequelize.define('task', { title: Sequelize.STRING }) 2608const User = this.sequelize.define('user', { username: Sequelize.STRING }) 2609 2610User.hasMany(Task) 2611Task.belongsTo(User)</code> 2612</code></pre><p>Will generate the following SQL:</p><pre><code class="lang-sql"><code class="source-code prettyprint">CREATE TABLE IF NOT EXISTS `User` ( 2613 `id` INTEGER PRIMARY KEY, 2614 `username` VARCHAR(255) 2615); 2616 2617CREATE TABLE IF NOT EXISTS `Task` ( 2618 `id` INTEGER PRIMARY KEY, 2619 `title` VARCHAR(255), 2620 `user_id` INTEGER REFERENCES `User` (`id`) ON DELETE SET NULL ON UPDATE CASCADE 2621);</code> 2622</code></pre><p>The relation between task and user injects the <code>user_id</code> foreign key on tasks, and marks it as a reference to the <code>User</code> table. By default <code>user_id</code> will be set to <code>NULL</code> if the referenced user is deleted, and updated if the id of the user id updated. These options can be overridden by passing <code>onUpdate</code> and <code>onDelete</code> options to the association calls. The validation options are <code>RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL</code>.</p><p>For 1:1 and 1:m associations the default option is <code>SET NULL</code> for deletion, and <code>CASCADE</code> for updates. For n:m, the default for both is <code>CASCADE</code>. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.</p><p>Adding constraints between tables means that tables must be created in the database in a certain order, when using <code>sequelize.sync</code>. If Task has a reference to User, the User table must be created before the Task table can be created. This can sometimes lead to circular references, where sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has a reference to its current version.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Document = this.sequelize.define('document', { 2623 author: Sequelize.STRING 2624}) 2625const Version = this.sequelize.define('version', { 2626 timestamp: Sequelize.DATE 2627}) 2628 2629Document.hasMany(Version) // This adds document_id to version 2630Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id'}) // This adds current_version_id to document</code> 2631</code></pre><p>However, the code above will result in the following error: <code>
2631Cyclic dependency found. 'Document' is dependent of itself. Dependency Chain: Document -> Version => Document</code>. In order to alleviate that, we can pass <code>constraints: false</code> to one of the associations:</p><pre><code class="lang-js"><code class="source-code prettyprint">Document.hasMany(Version) 2632Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id', constraints: false})</code> 2633</code></pre><p>Which will allow us to sync the tables correctly:</p><pre><code class="lang-sql"><code class="source-code prettyprint">CREATE TABLE IF NOT EXISTS `Document` ( 2634 `id` INTEGER PRIMARY KEY, 2635 `author` VARCHAR(255), 2636 `current_version_id` INTEGER 2637); 2638CREATE TABLE IF NOT EXISTS `Version` ( 2639 `id` INTEGER PRIMARY KEY, 2640 `timestamp` DATETIME, 2641 `document_id` INTEGER REFERENCES `Document` (`id`) ON DELETE SET NULL ON UPDATE CASCADE 2642);</code> 2643</code></pre><h3>Enforcing a foreign key reference without constraints</h3><p>Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.</p><pre><code class="lang-js"><code class="source-code prettyprint">// Series has a trainer_id=Trainer.id foreign reference key after we call Trainer.hasMany(series) 2644const Series = sequelize.define('series', { 2645 title: DataTypes.STRING, 2646 sub_title: DataTypes.STRING, 2647 description: DataTypes.TEXT, 2648 2649 // Set FK relationship (hasMany) with `Trainer` 2650 trainer_id: { 2651 type: DataTypes.INTEGER, 2652 references: { 2653 model: "trainer", 2654 key: "id" 2655 } 2656 } 2657}) 2658 2659const Trainer = sequelize.define('trainer', { 2660 first_name: DataTypes.STRING, 2661 last_name: DataTypes.STRING 2662}); 2663 2664// Video has a series_id=Series.id foreign reference key after we call Series.hasOne(Video)... 2665const Video = sequelize.define('video', { 2666 title: DataTypes.STRING, 2667 sequence: DataTypes.INTEGER, 2668 description: DataTypes.TEXT, 2669 2670 // set relationship (hasOne) with `Series` 2671 series_id: { 2672 type: DataTypes.INTEGER, 2673 references: { 2674 model: Series, // Can be both a string representing the table name, or a reference to the model 2675 key: "id" 2676 } 2677 } 2678}); 2679 2680Series.hasOne(Video); 2681Trainer.hasMany(Series);</code> 2682</code></pre><h2>Creating with associations</h2><p>An instance can be created with nested association in one step, provided all elements are new.</p><h3>Creating elements of a "BelongsTo", "Has Many" or "HasOne" association</h3><p>Consider the following models:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Product = this.sequelize.define('product', { 2683 title: Sequelize.STRING 2684}); 2685const User = this.sequelize.define('user', { 2686 first_name: Sequelize.STRING, 2687 last_name: Sequelize.STRING 2688}); 2689const Address = this.sequelize.define('address', { 2690 type: Sequelize.STRING, 2691 line_1: Sequelize.STRING, 2692 line_2: Sequelize.STRING, 2693 city: Sequelize.STRING, 2694 state: Sequelize.STRING, 2695 zip: Sequelize.STRING, 2696}); 2697 2698Product.User = Product.belongsTo(User); 2699User.Addresses = User.hasMany(Address); 2700// Also works for `hasOne`</code> 2701</code></pre><p>A new <code>Product</code>, <code>User</code>, and one or more <code>Address</code> can be created in one step in the following way:</p><pre><code class="lang-js"><code class="source-code prettyprint">return Product.create({ 2702 title: 'Chair', 2703 user: { 2704 first_name: 'Mick', 2705 last_name: 'Broadstone', 2706 addresses: [{ 2707 type: 'home', 2708 line_1: '100 Main St.', 2709 city: 'Austin', 2710 state: 'TX', 2711 zip: '78704' 2712 }] 2713 } 2714}, { 2715 include: [{ 2716 association: Product.User, 2717 include: [ User.Addresses ] 2718 }] 2719});</code> 2720</code></pre><p>Here, our user model is called <code>user</code>, with a lowercase u - This means that the property in the object should also be <code>user</code>. If the name given to <code>sequelize.define</code> was <code>User</code>, the key in the object should also be <code>User</code>. Likewise for <code>addresses</code>, except it's pluralized being a <code>hasMany</code> association.</p><h3>Creating elements of a "BelongsTo" association with an alias</h3><p>The previous example can be extended to support an association alias.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Creator = Product.belongsTo(User, {as: 'creator'}); 2721 2722return Product.create({ 2723 title: 'Chair', 2724 creator: { 2725 first_name: 'Matt', 2726 last_name: 'Hansen' 2727 } 2728}, { 2729 include: [ Creator ] 2730});</code> 2731</code></pre><h3>Creating elements of a "HasMany" or "BelongsToMany" association</h3><p>Let's introduce the ability to associate a product with many tags. Setting up the models could look like:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Tag = this.sequelize.define('tag', { 2732 name: Sequelize.STRING 2733}); 2734 2735Product.hasMany(Tag); 2736// Also works for `belongsToMany`.</code> 2737</code></pre><p>
2737Now we can create a product with multiple tags in the following way:</p><pre><code class="lang-js"><code class="source-code prettyprint">Product.create({ 2738 id: 1, 2739 title: 'Chair', 2740 tags: [ 2741 { name: 'Alpha'}, 2742 { name: 'Beta'} 2743 ] 2744}, { 2745 include: [ Tag ] 2746})</code> 2747</code></pre><p>And, we can modify this example to support an alias as well:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Categories = Product.hasMany(Tag, {as: 'categories'}); 2748 2749Product.create({ 2750 id: 1, 2751 title: 'Chair', 2752 categories: [ 2753 {id: 1, name: 'Alpha'}, 2754 {id: 2, name: 'Beta'} 2755 ] 2756}, { 2757 include: [{ 2758 model: Categories, 2759 as: 'categories' 2760 }] 2761})</code> 2762</code></pre><hr></div> 2763 <a data-ice='link' href='/v4/manual/tutorial/associations'></a> 2764 </div> 2765 </div> 2766<div class="manual-card-wrap" data-ice="cards"> 2767 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â "><span data-ice="label-inner">Transactions</span></h1> 2768 <div class="manual-card"> 2769 <div data-ice="card"><h1>Transactions</h1><p>Sequelize supports two ways of using transactions:</p><ul> 2770<li>One which will automatically commit or rollback the transaction based on the result of a promise chain and, (if enabled) pass the transaction to all calls within the callback</li> 2771<li>And one which leaves committing, rolling back and passing the transaction to the user.</li> 2772</ul><p>The key difference is that the managed transaction uses a callback that expects a promise to be returned to it while the unmanaged transaction returns a promise.</p><h2>Managed transaction (auto-callback)</h2><p>Managed transactions handle committing or rolling back the transaction automagically. You start a managed transaction by passing a callback to <code>sequelize.transaction</code>.</p><p>Notice how the callback passed to <code>transaction</code> returns a promise chain, and does not explicitly call <code>t.commit()</code> nor <code>t.rollback()</code>. If all promises in the returned chain are resolved successfully the transaction is committed. If one or several of the promises are rejected, the transaction is rolled back.</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction(function (t) { 2773 2774 // chain all your queries here. make sure you return them. 2775 return User.create({ 2776 firstName: 'Abraham', 2777 lastName: 'Lincoln' 2778 }, {transaction: t}).then(function (user) { 2779 return user.setShooter({ 2780 firstName: 'John', 2781 lastName: 'Boothe' 2782 }, {transaction: t}); 2783 }); 2784 2785}).then(function (result) { 2786 // Transaction has been committed 2787 // result is whatever the result of the promise chain returned to the transaction callback 2788}).catch(function (err) { 2789 // Transaction has been rolled back 2790 // err is whatever rejected the promise chain returned to the transaction callback 2791});</code> 2792</code></pre><h3>Throw errors to rollback</h3><p>When using the managed transaction you should <em>never</em> commit or rollback the transaction manually. If all queries are successful, but you still want to rollback the transaction (for example because of a validation failure) you should throw an error to break and reject the chain:</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction(function (t) { 2793 return User.create({ 2794 firstName: 'Abraham', 2795 lastName: 'Lincoln' 2796 }, {transaction: t}).then(function (user) { 2797 // Woops, the query was successful but we still want to roll back! 2798 throw new Error(); 2799 }); 2800});</code> 2801</code></pre><h3>Automatically pass transactions to all queries</h3><p>In the examples above, the transaction is still manually passed, by passing <code>{ transaction: t }</code> as the second argument. To automatically pass the transaction to all queries you must install the <a href="https://github.com/othiym23/node-continuation-local-storage">continuation local storage</a> (CLS) module and instantiate a namespace in your own code:</p><pre><code class="lang-js"><code class="source-code prettyprint">const cls = require('continuation-local-storage'), 2802 namespace = cls.createNamespace('my-very-own-namespace');</code> 2803</code></pre><p>To enable CLS you must tell sequelize which namespace to use by using a static method of the sequelize constructor:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Sequelize = require('sequelize'); 2804Sequelize.useCLS(namespace); 2805 2806new Sequelize(....);</code> 2807</code></pre><p>Notice, that the <code>useCLS()</code> method is on the <em>constructor</em>, not on an instance of sequelize. This means that all instances will share the same namespace, and that CLS is all-or-nothing - you cannot enable it only for some instances.</p><p>CLS works like a thread-local storage for callbacks. What this means in practice is that different callback chains can access local variables by using the CLS namespace. When CLS is enabled sequelize will set the <code>transaction</code> property on the namespace when a new transaction is created. Since variables set within a callback chain are private to that chain several concurrent transactions can exist at the same time:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction(function (t1) { 2808 namespace.get('transaction') === t1; // true 2809}); 2810 2811sequelize.transaction(function (t2) { 2812 namespace.get('transaction') === t2; // true 2813});</code> 2814</code></pre><p>In most case you won't need to access <code>namespace.get('transaction')</code> directly, since all queries will automatically look for a transaction on the namespace:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction(function (t1) { 2815 // With CLS enabled, the user will be created inside the transaction 2816 return User.create({ name: 'Alice' }); 2817});</code> 2818</code></pre><p>After you've used <code>Sequelize.useCLS()</code> all promises returned from sequelize will be patched to maintain CLS context. CLS is a complicated subject - more details in the docs for <a href="https://www.npmjs.com/package/cls-bluebird">cls-bluebird</a>, the patch used to make bluebird promises work with CLS.</p><p><strong>Note:</strong> _<a href="https://github.com/othiym23/node-continuation-local-storage/issues/98#issuecomment-323503807">CLS only supports async/await, at the moment, when using cls-hooked package</a>. Although, <a href="https://github.com/Jeff-Lewis/cls-hooked/blob/master/README.md">cls-hooked</a> relies on <em>experimental API</em> <a href="https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md">async_hooks</a>_</p><h2>Concurrent/Partial transactions</h2><p>You can have concurrent transactions within a sequence of queries or have some of them excluded from any transactions. Use the <code>{transaction: }</code> option to control which transaction a query belong to:</p><p><strong>Warning:</strong> <em>SQLite does not support more than one transaction at the same time.</em></p><h3>Without CLS enabled</h3><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction(function (t1) { 2819 return sequelize.transaction(function (t2) { 2820 // With CLS enable, queries here will by default use t2 2821 // Pass in the `transaction` option to define/alter the transaction they belong to. 2822 return Promise.all([ 2823 User.create({ name: 'Bob' }, { transaction: null }), 2824 User.create({ name: 'Mallory' }, { transaction: t1 }), 2825 User.create({ name: 'John' }) // this would default to t2 2826 ]); 2827 }); 2828});</code> 2829</code></pre><h2>Isolation levels</h2><p>The possible isolations levels to use when starting a transaction:</p><pre><code class="lang-js"><code class="source-code prettyprint">Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED // "READ UNCOMMITTED"
2830Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED // "READ COMMITTED" 2831Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ // "REPEATABLE READ" 2832Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE // "SERIALIZABLE"</code> 2833</code></pre><p>By default, sequelize uses the isolation level of the database. If you want to use a different isolation level, pass in the desired level as the first argument:</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction({ 2834 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE 2835 }, function (t) { 2836 2837 // your transactions 2838 2839 });</code> 2840</code></pre><p><strong>Note:</strong> <em>The SET ISOLATION LEVEL queries are not logged in case of MSSQL as the specified isolationLevel is passed directly to tedious</em></p><h2>Unmanaged transaction (then-callback)</h2><p>Unmanaged transactions force you to manually rollback or commit the transaction. If you don't do that, the transaction will hang until it times out. To start an unmanaged transaction, call <code>sequelize.transaction()</code> without a callback (you can still pass an options object) and call <code>then</code> on the returned promise. Notice that <code>commit()</code> and <code>rollback()</code> returns a promise.</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction().then(function (t) { 2841 return User.create({ 2842 firstName: 'Bart', 2843 lastName: 'Simpson' 2844 }, {transaction: t}).then(function (user) { 2845 return user.addSibling({ 2846 firstName: 'Lisa', 2847 lastName: 'Simpson' 2848 }, {transaction: t}); 2849 }).then(function () { 2850 return t.commit(); 2851 }).catch(function (err) { 2852 return t.rollback(); 2853 }); 2854});</code> 2855</code></pre><h2>Options</h2><p>The <code>transaction</code> method can be called with an options object as the first argument, that 2856allows the configuration of the transaction.</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction({ /* options */ });</code> 2857</code></pre><p>The following options (with their default values) are available:</p><pre><code class="lang-js"><code class="source-code prettyprint">{ 2858 autocommit: true, 2859 isolationLevel: 'REPEATABLE_READ', 2860 deferrable: 'NOT DEFERRABLE' // implicit default of postgres 2861}</code> 2862</code></pre><p>The <code>isolationLevel</code> can either be set globally when initializing the Sequelize instance or 2863locally for every transaction:</p><pre><code class="lang-js"><code class="source-code prettyprint">// globally 2864new Sequelize('db', 'user', 'pw', { 2865 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE 2866}); 2867 2868// locally 2869sequelize.transaction({ 2870 isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE 2871});</code> 2872</code></pre><p>The <code>deferrable</code> option triggers an additional query after the transaction start 2873that optionally set the constraint checks to be deferred or immediate. Please note 2874that this is only supported in PostgreSQL.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction({ 2875 // to defer all constraints: 2876 deferrable: Sequelize.Deferrable.SET_DEFERRED, 2877 2878 // to defer a specific constraint: 2879 deferrable: Sequelize.Deferrable.SET_DEFERRED(['some_constraint']), 2880 2881 // to not defer constraints: 2882 deferrable: Sequelize.Deferrable.SET_IMMEDIATE 2883})</code> 2884</code></pre><h2>Usage with other sequelize methods</h2><p>The <code>transaction</code> option goes with most other options, which are usually the first argument of a method. 2885For methods that take values, like <code>.create</code>, <code>.update()</code>, <code>.updateAttributes()</code> etc. <code>transaction</code> should be passed to the option in the second argument. 2886If unsure, refer to the API documentation for the method you are using to be sure of the signature.</p><h2>After commit hook</h2><p>A <code>transaction</code> object allows tracking if and when it is committed.</p><p>An <code>afterCommit</code> hook can be added to both managed and unmanaged transaction objects:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction(t => { 2887 t.afterCommit((transaction) => { 2888 // Your logic 2889 }); 2890}); 2891 2892sequelize.transaction().then(t => { 2893 t.afterCommit((transaction) => { 2894 // Your logic 2895 }); 2896 2897 return t.commit(); 2898})</code> 2899</code></pre><p>The function passed to <code>afterCommit</code> can optionally return a promise that will resolve before the promise chain 2900that created the transaction resolves</p><p><code>afterCommit</code> hooks are <em>not</em> raised if a transaction is rolled back</p><p><code>afterCommit</code> hooks do <em>not</em> modify the return value of the transaction, unlike standard hooks</p><p>You can use the <code>afterCommit</code> hook in conjunction with model hooks to know when a instance is saved and available outside 2901of a transaction</p><p>```js 2902model.afterSave((instance, options) => { 2903 if (options.transaction) { 2904 // Save done within a transaction, wait until transaction is committed to 2905 // notify listeners the instance has been saved 2906 options.transaction.afterCommit(() => /<em> Notify </em>/) 2907 return; 2908 } 2909 // Save done outside a transaction, safe for callers to fetch the updated model 2910 // Notify</p></div> 2911 <a data-ice='link' href='/v4/manual/tutorial/transactions'></a> 2912 </div> 2913 </div> 2914<div class="manual-card-wrap" data-ice="cards"> 2915 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â "><span data-ice="label-inner">Scopes</span></h1> 2916 <div class="manual-card"> 2917 <div data-ice="card"><h1>Scopes</h1><p>Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders, <code>where</code>, <code>include</code>, <code>limit</code> etc.</p><h2>Definition</h2><p>Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Project = sequelize.define('project', { 2918 // Attributes 2919}, { 2920 defaultScope: { 2921 where: { 2922 active: true 2923 } 2924 }, 2925 scopes: { 2926 deleted: { 2927 where: { 2928 deleted: true 2929 } 2930 }, 2931 activeUsers: { 2932 include: [ 2933 { model: User, where: { active: true }} 2934 ] 2935 }, 2936 random: function () { 2937 return { 2938 where: { 2939 someNumber: Math.random() 2940 } 2941 } 2942 }, 2943 accessLevel: function (value) { 2944 return { 2945 where: { 2946 accessLevel: { 2947 [Op.gte]: value 2948 } 2949 } 2950 } 2951 } 2952 } 2953});</code> 2954</code></pre><p>You can also add scopes after a model has been defined by calling <code>addScope</code>. This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.</p><p>The default scope is always applied. This means, that with the model definition above, <code>
2954Project.findAll()</code> will create the following query:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE active = true</code> 2955</code></pre><p>The default scope can be removed by calling <code>.unscoped()</code>, <code>.scope(null)</code>, or by invoking another scope:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('deleted').findAll(); // Removes the default scope</code> 2956</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE deleted = true</code> 2957</code></pre><p>It is also possible to include scoped models in a scope definition. This allows you to avoid duplicating <code>include</code>, <code>attributes</code> or <code>where</code> definitions. 2958Using the above example, and invoking the <code>active</code> scope on the included User model (rather than specifying the condition directly in that include object):</p><pre><code class="lang-js"><code class="source-code prettyprint">activeUsers: { 2959 include: [ 2960 { model: User.scope('active')} 2961 ] 2962}</code> 2963</code></pre><h2>Usage</h2><p>Scopes are applied by calling <code>.scope</code> on the model definition, passing the name of one or more scopes. <code>.scope</code> returns a fully functional model instance with all the regular methods: <code>.findAll</code>, <code>.update</code>, <code>.count</code>, <code>.destroy</code> etc. You can save this model instance and reuse it later:</p><pre><code class="lang-js"><code class="source-code prettyprint">const DeletedProjects = Project.scope('deleted'); 2964 2965DeletedProjects.findAll(); 2966// some time passes 2967 2968// let's look for deleted projects again! 2969DeletedProjects.findAll();</code> 2970</code></pre><p>Scopes apply to <code>.find</code>, <code>.findAll</code>, <code>.count</code>, <code>.update</code>, <code>.increment</code> and <code>.destroy</code>.</p><p>Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('random', { method: ['accessLevel', 19]}).findAll();</code> 2971</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE someNumber = 42 AND accessLevel >= 19</code> 2972</code></pre><h2>Merging</h2><p>Several scopes can be applied simultaneously by passing an array of scopes to <code>.scope</code>, or by passing the scopes as consecutive arguments.</p><pre><code class="lang-js"><code class="source-code prettyprint">// These two are equivalent 2973Project.scope('deleted', 'activeUsers').findAll(); 2974Project.scope(['deleted', 'activeUsers']).findAll();</code> 2975</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects 2976INNER JOIN users ON projects.userId = users.id 2977AND users.active = true</code> 2978</code></pre><p>If you want to apply another scope alongside the default scope, pass the key <code>defaultScope</code> to <code>.scope</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('defaultScope', 'deleted').findAll();</code> 2979</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE active = true AND deleted = true</code> 2980</code></pre><p>When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similar to <a href="https://lodash.com/docs#assign">_.assign</a>). Consider two scopes:</p><pre><code class="lang-js"><code class="source-code prettyprint">{ 2981 scope1: { 2982 where: { 2983 firstName: 'bob', 2984 age: { 2985 [Op.gt]: 20 2986 } 2987 }, 2988 limit: 2 2989 }, 2990 scope2: { 2991 where: { 2992 age: { 2993 [Op.gt]: 30 2994 } 2995 }, 2996 limit: 10 2997 } 2998}</code> 2999</code></pre><p>Calling <code>.scope('scope1', 'scope2')</code> will yield the following query</p><pre><code class="lang-sql"><code class="source-code prettyprint">WHERE firstName = 'bob' AND age > 30 LIMIT 10</code> 3000</code></pre><p>Note how <code>limit</code> and <code>age</code> are overwritten by <code>scope2</code>, while <code>firstName</code> is preserved. <code>limit</code>, <code>offset</code>, <code>order</code>, <code>paranoid</code>, <code>lock</code> and <code>raw</code> are overwritten, while <code>where</code> and <code>include</code> are shallowly merged. This means that identical keys in the where objects, and subsequent includes of the same model will both overwrite each other.</p><p>The same merge logic applies when passing a find object directly to findAll on a scoped model:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('deleted').findAll({ 3001 where: { 3002 firstName: 'john' 3003 } 3004})</code> 3005</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">WHERE deleted = true AND firstName = 'john'</code> 3006</code></pre><p>Here the <code>deleted</code> scope is merged with the finder. If we were to pass <code>where: { firstName: 'john', deleted: false }</code> to the finder, the <code>deleted</code>
3006 scope would be overwritten.</p><h2>Associations</h2><p>Sequelize has two different but related scope concepts in relation to associations. The difference is subtle but important:</p><ul> 3007<li><strong>Association scopes</strong> Allow you to specify default attributes when getting and setting associations - useful when implementing polymorphic associations. This scope is only invoked on the association between the two models, when using the <code>get</code>, <code>set</code>, <code>add</code> and <code>create</code> associated model functions</li> 3008<li><strong>Scopes on associated models</strong> Allows you to apply default and other scopes when fetching associations, and allows you to pass a scoped model when creating associations. These scopes both apply to regular finds on the model and to find through the association.</li> 3009</ul><p>As an example, consider the models Post and Comment. Comment is associated to several other models (Image, Video etc.) and the association between Comment and other models is polymorphic, which means that Comment stores a <code>commentable</code> column, in addition to the foreign key <code>commentable_id</code>.</p><p>The polymorphic association can be implemented with an <em>association scope</em> :</p><pre><code class="lang-js"><code class="source-code prettyprint">this.Post.hasMany(this.Comment, { 3010 foreignKey: 'commentable_id', 3011 scope: { 3012 commentable: 'post' 3013 } 3014});</code> 3015</code></pre><p>When calling <code>post.getComments()</code>, this will automatically add <code>WHERE commentable = 'post'</code>. Similarly, when adding new comments to a post, <code>commentable</code> will automagically be set to <code>'post'</code>. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see <a href='/v4/manual/tutorial/associations#scopes'>Association scopes</a></p><p>Consider then, that Post has a default scope which only shows active posts: <code>where: { active: true }</code>. This scope lives on the associated model (Post), and not on the association like the <code>commentable</code> scope did. Just like the default scope is applied when calling <code>Post.findAll()</code>, it is also applied when calling <code>User.getPosts()</code> - this will only return the active posts for that user.</p><p>To disable the default scope, pass <code>scope: null</code> to the getter: <code>User.getPosts({ scope: null })</code>. Similarly, if you want to apply other scopes, pass an array like you would to <code>.scope</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.getPosts({ scope: ['scope1', 'scope2']});</code> 3016</code></pre><p>If you want to create a shortcut method to a scope on an associated model, you can pass the scoped model to the association. Consider a shortcut to get all deleted posts for a user:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Post = sequelize.define('post', attributes, { 3017 defaultScope: { 3018 where: { 3019 active: true 3020 } 3021 }, 3022 scopes: { 3023 deleted: { 3024 where: { 3025 deleted: true 3026 } 3027 } 3028 } 3029}); 3030 3031User.hasMany(Post); // regular getPosts association 3032User.hasMany(Post.scope('deleted'), { as: 'deletedPosts' });</code> 3033</code></pre><pre><code class="lang-js"><code class="source-code prettyprint">User.getPosts(); // WHERE active = true 3034User.getDeletedPosts(); // WHERE deleted = true</code> 3035</code></pre></div> 3036 <a data-ice='link' href='/v4/manual/tutorial/scopes'></a> 3037 </div> 3038 </div> 3039<div class="manual-card-wrap" data-ice="cards"> 3040 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â "><span data-ice="label-inner">Hooks</span></h1> 3041 <div class="manual-card"> 3042 <div data-ice="card"><h1>Hooks</h1><p>Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a <code>beforeUpdate</code> hook.</p><p>For a full list of hooks, see <a href="https://github.com/sequelize/sequelize/blob/master/lib/hooks.js#L7">Hooks file</a>.</p><h2>Order of Operations</h2><pre><code><code class="source-code prettyprint">(1) 3043 beforeBulkCreate(instances, options) 3044 beforeBulkDestroy(options) 3045 beforeBulkUpdate(options) 3046(2) 3047 beforeValidate(instance, options) 3048(-) 3049 validate 3050(3) 3051 afterValidate(instance, options) 3052 - or - 3053 validationFailed(instance, options, error) 3054(4) 3055 beforeCreate(instance, options) 3056 beforeDestroy(instance, options) 3057 beforeUpdate(instance, options) 3058 beforeSave(instance, options) 3059 beforeUpsert(values, options) 3060(-) 3061 create 3062 destroy 3063 update 3064(5) 3065 afterCreate(instance, options) 3066 afterDestroy(instance, options) 3067 afterUpdate(instance, options) 3068 afterSave(instance, options) 3069 afterUpsert(created, options) 3070(6) 3071 afterBulkCreate(instances, options) 3072 afterBulkDestroy(options) 3073 afterBulkUpdate(options)</code> 3074</code></pre><h2>Declaring Hooks</h2><p>Arguments to hooks are passed by reference. This means, that you can change the values, and this will be reflected in the insert / update statement. A hook may contain async actions - in this case the hook function should return a promise.</p><p>There are currently three ways to programmatically add hooks:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Method 1 via the .define() method 3075const User = sequelize.define('user', { 3076 username: DataTypes.STRING, 3077 mood: { 3078 type: DataTypes.ENUM, 3079 values: ['happy', 'sad', 'neutral'] 3080 } 3081}, { 3082 hooks: { 3083 beforeValidate: (user, options) => { 3084 user.mood = 'happy'; 3085 }, 3086 afterValidate: (user, options) => { 3087 user.username = 'Toni'; 3088 } 3089 } 3090}); 3091 3092// Method 2 via the .hook() method (or its alias .addHook() method) 3093User.hook('beforeValidate', (user, options) => { 3094 user.mood = 'happy'; 3095}); 3096 3097User.addHook('afterValidate', 'someCustomName', (user, options) => { 3098 return sequelize.Promise.reject(new Error("I'm afraid I can't let you do that!")); 3099}); 3100 3101// Method 3 via the direct method 3102User.beforeCreate((user, options) => { 3103 return hashPassword(user.password).then(hashedPw => { 3104 user.password = hashedPw; 3105 }); 3106}); 3107 3108User.afterValidate('myHookAfter', (user, options) => { 3109 user.username = 'Toni'; 3110});</code> 3111</code></pre><h2>Removing hooks</h2><p>
3111Only a hook with name param can be removed.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Book = sequelize.define('book', { 3112 title: DataTypes.STRING 3113}); 3114 3115Book.addHook('afterCreate', 'notifyUsers', (book, options) => { 3116 // ... 3117}); 3118 3119Book.removeHook('afterCreate', 'notifyUsers');</code> 3120</code></pre><p>You can have many hooks with same name. Calling <code>.removeHook()</code> will remove all of them.</p><h2>Global / universal hooks</h2><p>Global hooks are hooks which are run for all models. They can define behaviours that you want for all your models, and are especially useful for plugins. They can be defined in two ways, which have slightly different semantics:</p><h3>Sequelize.options.define (default hook)</h3><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize(..., { 3121 define: { 3122 hooks: { 3123 beforeCreate: () => { 3124 // Do stuff 3125 } 3126 } 3127 } 3128});</code> 3129</code></pre><p>This adds a default hook to all models, which is run if the model does not define its own <code>beforeCreate</code> hook:</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = sequelize.define('user'); 3130const Project = sequelize.define('project', {}, { 3131 hooks: { 3132 beforeCreate: () => { 3133 // Do other stuff 3134 } 3135 } 3136}); 3137 3138User.create() // Runs the global hook 3139Project.create() // Runs its own hook (because the global hook is overwritten)</code> 3140</code></pre><h3>Sequelize.addHook (permanent hook)</h3><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.addHook('beforeCreate', () => { 3141 // Do stuff 3142});</code> 3143</code></pre><p>This hooks is always run before create, regardless of whether the model specifies its own <code>beforeCreate</code> hook:</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = sequelize.define('user'); 3144const Project = sequelize.define('project', {}, { 3145 hooks: { 3146 beforeCreate: () => { 3147 // Do other stuff 3148 } 3149 } 3150}); 3151 3152User.create() // Runs the global hook 3153Project.create() // Runs its own hook, followed by the global hook</code> 3154</code></pre><p>Local hooks are always run before global hooks.</p><h3>Instance hooks</h3><p>The following hooks will emit whenever you're editing a single object</p><pre><code><code class="source-code prettyprint">beforeValidate 3155afterValidate or validationFailed 3156beforeCreate / beforeUpdate / beforeDestroy 3157afterCreate / afterUpdate / afterDestroy</code> 3158</code></pre><pre><code class="lang-js"><code class="source-code prettyprint">// ...define ... 3159User.beforeCreate(user => { 3160 if (user.accessLevel > 10 && user.username !== "Boss") { 3161 throw new Error("You can't grant this user an access level above 10!") 3162 } 3163})</code> 3164</code></pre><p>This example will return an error:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({username: 'Not a Boss', accessLevel: 20}).catch(err => { 3165 console.log(err); // You can't grant this user an access level above 10! 3166});</code> 3167</code></pre><p>The following example would return successful:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({username: 'Boss', accessLevel: 20}).then(user => { 3168 console.log(user); // user object with username as Boss and accessLevel of 20 3169});</code> 3170</code></pre><h3>Model hooks</h3><p>Sometimes you'll be editing more than one record at a time by utilizing the <code>bulkCreate, update, destroy</code> methods on the model. The following will emit whenever you're using one of those methods:</p><pre><code><code class="source-code prettyprint">beforeBulkCreate(instances, options) 3171beforeBulkUpdate(options) 3172beforeBulkDestroy(options) 3173afterBulkCreate(instances, options) 3174afterBulkUpdate(options) 3175afterBulkDestroy(options)</code> 3176</code></pre><p>If you want to emit hooks for each individual record, along with the bulk hooks you can pass <code>individualHooks: true</code> to the call.</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.destroy({ where: {accessLevel: 0}, individualHooks: true}); 3177// Will select all records that are about to be deleted and emit before- + after- Destroy on each instance 3178 3179Model.update({username: 'Toni'}, { where: {accessLevel: 0}, individualHooks: true}); 3180// Will select all records that are about to be updated and emit before- + after- Update on each instance</code> 3181</code></pre><p>The <code>options</code> argument of hook method would be the second argument provided to the corresponding method or its 3182cloned and extended version.</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.beforeBulkCreate((records, {fields}) => { 3183 // records = the first argument sent to .bulkCreate
3184 // fields = one of the second argument fields sent to .bulkCreate 3185}) 3186 3187Model.bulkCreate([ 3188 {username: 'Toni'}, // part of records argument 3189 {username: 'Tobi'} // part of records argument 3190 ], {fields: ['username']} // options parameter 3191) 3192 3193Model.beforeBulkUpdate(({attributes, where}) => { 3194 // where - in one of the fields of the clone of second argument sent to .update 3195 // attributes - is one of the fields that the clone of second argument of .update would be extended with 3196}) 3197 3198Model.update({gender: 'Male'} /*attributes argument*/, { where: {username: 'Tom'}} /*where argument*/) 3199 3200Model.beforeBulkDestroy(({where, individualHooks}) => { 3201 // individualHooks - default of overridden value of extended clone of second argument sent to Model.destroy 3202 // where - in one of the fields of the clone of second argument sent to Model.destroy 3203}) 3204 3205Model.destroy({ where: {username: 'Tom'}} /*where argument*/)</code> 3206</code></pre><p>If you use <code>Model.bulkCreate(...)</code> with the <code>updatesOnDuplicate</code> option, changes made in the hook to fields that aren't given in the <code>updatesOnDuplicate</code> array will not be persisted to the database. However it is possible to change the updatesOnDuplicate option inside the hook if this is what you want.</p><pre><code class="lang-js"><code class="source-code prettyprint">// Bulk updating existing users with updatesOnDuplicate option 3207Users.bulkCreate([ 3208 { id: 1, isMember: true }, 3209 { id: 2, isMember: false } 3210], { 3211 updatesOnDuplicate: ['isMember'] 3212}); 3213 3214User.beforeBulkCreate((users, options) => { 3215 for (const user of users) { 3216 if (user.isMember) { 3217 user.memberSince = new Date(); 3218 } 3219 } 3220 3221 // Add memberSince to updatesOnDuplicate otherwise the memberSince date wont be 3222 // saved to the database 3223 options.updatesOnDuplicate.push('memberSince'); 3224});</code> 3225</code></pre><h2>Associations</h2><p>For the most part hooks will work the same for instances when being associated except a few things</p><ol> 3226<li>When using add/set functions the beforeUpdate/afterUpdate hooks will run.</li> 3227<li>The only way to call beforeDestroy/afterDestroy hooks are on associations with <code>onDelete: 'cascade'</code> and the option <code>hooks: true</code>. For instance:</li> 3228</ol><pre><code class="lang-js"><code class="source-code prettyprint">const Projects = sequelize.define('projects', { 3229 title: DataTypes.STRING 3230}); 3231 3232const Tasks = sequelize.define('tasks', { 3233 title: DataTypes.STRING 3234}); 3235 3236Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true }); 3237Tasks.belongsTo(Projects);</code> 3238</code></pre><p>This code will run beforeDestroy/afterDestroy on the Tasks table. Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute a</p><pre><code class="lang-sql"><code class="source-code prettyprint">DELETE FROM `table` WHERE associatedIdentifier = associatedIdentifier.primaryKey</code> 3239</code></pre><p>However, adding <code>hooks: true</code> explicitly tells Sequelize that optimization is not of your concern and will perform a <code>SELECT</code> on the associated objects and destroy each instance one by one in order to be able to call the hooks with the right parameters.</p><p>If your association is of type <code>n:m</code>, you may be interested in firing hooks on the through model when using the <code>remove</code> call. Internally, sequelize is using <code>Model.destroy</code> resulting in calling the <code>bulkDestroy</code> instead of the <code>before/afterDestroy</code> hooks on each through instance.</p><p>This can be simply solved by passing <code>{individualHooks: true}</code> to the <code>remove</code> call, resulting on each hook to be called on each removed through instance object.</p><h2>A Note About Transactions</h2><p>Note that many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction <em>is</em> specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Here we use the promise-style of async hooks rather than 3240// the callback. 3241User.hook('afterCreate', (user, options) => { 3242 // 'transaction' will be available in options.transaction 3243 3244 // This operation will be part of the same transaction as the 3245 // original User.create call. 3246 return User.update({ 3247 mood: 'sad' 3248 }, { 3249 where: { 3250 id: user.id 3251 }, 3252 transaction: options.transaction 3253 }); 3254}); 3255 3256 3257sequelize.transaction(transaction => { 3258 User.create({ 3259 username: 'someguy', 3260 mood: 'happy', 3261 transaction 3262 }); 3263});</code> 3264</code></pre><p>If we had not included the transaction option in our call to <code>User.update</code> in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.</p><h3>Internal Transactions</h3><p>
3264It is very important to recognize that sequelize may make use of transactions internally for certain operations such as <code>Model.findOrCreate</code>. If your hook functions execute read or write operations that rely on the object's presence in the database, or modify the object's stored values like the example in the preceding section, you should always specify <code>{ transaction: options.transaction }</code>.</p><p>If the hook has been called in the process of a transacted operation, this makes sure that your dependent read/write is a part of that same transaction. If the hook is not transacted, you have simply specified <code>{ transaction: null }</code> and can expect the default behaviour.</p></div> 3265 <a data-ice='link' href='/v4/manual/tutorial/hooks'></a> 3266 </div> 3267 </div> 3268<div class="manual-card-wrap" data-ice="cards"> 3269 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â "><span data-ice="label-inner">Raw queries</span></h1> 3270 <div class="manual-card"> 3271 <div data-ice="card"><h1>Raw queries</h1><p>As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function <code>sequelize.query</code>.</p><p>By default the function will return two arguments - a results array, and an object c
3271ontaining metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread((results, metadata) => { 3272 // Results will be an empty array and metadata will contain the number of affected rows. 3273})</code> 3274</code></pre><p>In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT}) 3275 .then(users => { 3276 // We don't need spread here, since only the results will be returned for select queries 3277 })</code> 3278</code></pre><p>Several other query types are available. <a href="https://github.com/sequelize/sequelize/blob/master/lib/query-types.js">Peek into the source for details</a></p><p>A second option is the model. If you pass a model the returned data will be instances of that model.</p><pre><code class="lang-js"><code class="source-code prettyprint">// Callee is the model definition. This allows you to easily map a query to a predefined model 3279sequelize 3280 .query('SELECT * FROM projects', { 3281 model: Projects, 3282 mapToModel: true // pass true here if you have any mapped fields 3283 }) 3284 .then(projects => { 3285 // Each record will now be an instance of Project 3286 })</code> 3287</code></pre><h2>Replacements</h2><p>Replacements in a query can be done in two different ways, either using named parameters (starting with <code>:</code>), or unnamed, represented by a <code>?</code>. Replacements are passed in the options object.</p><ul> 3288<li>If an array is passed, <code>?</code> will be replaced in the order that they appear in the array</li> 3289<li>If an object is passed, <code>:key</code> will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.</li> 3290</ul><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT * FROM projects WHERE status = ?', 3291 { replacements: ['active'], type: sequelize.QueryTypes.SELECT } 3292).then(projects => { 3293 console.log(projects) 3294}) 3295 3296sequelize.query('SELECT * FROM projects WHERE status = :status ', 3297 { replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT } 3298).then(projects => { 3299 console.log(projects) 3300})</code> 3301</code></pre><p>Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT * FROM projects WHERE status IN(:status) ', 3302 { replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT } 3303).then(projects => { 3304 console.log(projects) 3305})</code> 3306</code></pre><p>To use the wildcard operator %, append it to your replacement. The following query matches users with names that start with 'ben'.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ', 3307 { replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT } 3308).then(projects => { 3309 console.log(projects) 3310})</code> 3311</code></pre><h2>Bind Parameter</h2><p>Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.</p><ul> 3312<li>If an array is passed, <code>$1</code> is bound to the 1st element in the array (<code>bind[0]</code>)</li> 3313<li>If an object is passed, <code>$key</code> is bound to <code>object['key']</code>. Each key must begin with a non-numeric char. <code>$1</code> is not a valid key, even if <code>object['1']</code> exists.</li> 3314<li>In either case <code>$$</code> can be used to escape a literal <code>$</code> sign.</li> 3315</ul><p>The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.</p><p>The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may al
3315so be needed to typecast them, if the type cannot be inferred from the context <code>$1::varchar</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1', 3316 { bind: ['active'], type: sequelize.QueryTypes.SELECT } 3317).then(projects => { 3318 console.log(projects) 3319}) 3320 3321sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status', 3322 { bind: { status: 'active' }, type: sequelize.QueryTypes.SELECT } 3323).then(projects => { 3324 console.log(projects) 3325})</code> 3326</code></pre></div> 3327 <a data-ice='link' href='/v4/manual/tutorial/raw-queries'></a> 3328 </div> 3329 </div> 3330<div class="manual-card-wrap" data-ice="cards"> 3331 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â â â "><span data-ice="label-inner">Migrations</span></h1> 3332 <div class="manual-card"> 3333 <div data-ice="card"><h1>Migrations</h1><p>Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.</p><p>You will need <a href="https://github.com/sequelize/cli">Sequelize CLI</a>. The CLI ships support for migrations and project bootstrapping.</p><h2>The CLI</h2><h3>Installing CLI</h3><p>Let's start with installing CLI, you can find instructions <a href="https://github.com/sequelize/cli">here</a>. Most preferred way is installing locally like this</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npm install --save sequelize-cli</code> 3334</code></pre><h3>Bootstrapping</h3><p>To create an empty project you will need to execute <code>init</code> command</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize init</code> 3335</code></pre><p>This will create following folders</p><ul> 3336<li><code>config</code>, contains config file, which tells CLI how to connect with database</li> 3337<li><code>models</code>, contains all models for your project</li> 3338<li><code>migrations</code>, contains all migration files</li> 3339<li><code>seeders</code>, contains all seed files</li> 3340</ul><h4>Configuration</h4><p>Before continuing further we will need to tell CLI how to connect to database. To do that let's open default config file <code>config/config.json</code>. It looks something like this</p><pre><code class="lang-json"><code class="source-code prettyprint">{ 3341 "development": { 3342 "username": "root", 3343 "password": null, 3344 "database": "database_development", 3345 "host": "127.0.0.1", 3346 "dialect": "mysql" 3347 }, 3348 "test": { 3349 "username": "root", 3350 "password": null, 3351 "database": "database_test", 3352 "host": "127.0.0.1", 3353 "dialect": "mysql" 3354 }, 3355 "production": { 3356 "username": "root", 3357 "password": null, 3358 "database": "database_test", 3359 "host": "127.0.0.1", 3360 "dialect": "mysql" 3361 } 3362}</code> 3363</code></pre><p>Now edit this file and set correct database credentials and dialect.</p><p><strong>Note:</strong> <em>If your database doesn't exists yet, you can just call <code>db:create</code> command. With proper access it will create that database for you.</em></p><h3>Creating first Model (and Migration)</h3><p>Once you have properly configured CLI config file you are ready to create your first migration. It's as simple as executing a simple command.</p><p>We will use <code>model:generate</code> command. This command requires two options</p><ul> 3364<li><code>name</code>, Name of the model</li> 3365<li><code>attributes</code>, List of model attributes</li> 3366</ul><p>Let's create a model named <code>User</code>.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string</code> 3367</code></pre><p>This will do following</p><ul> 3368<li>Create a model file <code>user</code> in <code>models</code> folder</li> 3369<li>Create a migration file with name like <code>XXXXXXXXXXXXXX-create-user.js</code> in <code>migrations</code> folder</li> 3370</ul><p><strong>Note:</strong> <em>Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.</em></p><h3>Running Migrations</h3><p>Until this step, we haven't inserted anything into the database. We have just created required model and migration files for our first model <code>User</code>. Now to actually create that table in database you need to run <code>db:migrate</code> command.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize db:migrate</code> 3371</code></pre><p>This command will execute these steps:</p><ul> 3372<li>Will ensure a table called <code>SequelizeMeta</code> in database. This table is used to record which migrations have run on the current database</li> 3373<li>Start looking for any migration files which haven't run yet. This is possible by checking <code>SequelizeMeta</code> table. In this case it will run <code>XXXXXXXXXXXXXX-create-user.js</code> migration, which we created in last step.</li> 3374<li>Creates a table called <code>Users</code> with all columns as specified in its migration file.</li> 3375</ul><h3>Undoing Migrations</h3><p>Now our table has been created and saved in database. With migration you can revert to old state by just running a command.</p><p>You can use <code>db:migrate:undo</code>, this command will revert most recent migration.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize db:migrate:undo</code> 3376</code></pre><p>You can revert back to initial state by undoing all migrations with <code>db:migrate:undo:all</code> command. You can also revert back to a specific migration by passing its name in <code>--to</code> option.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js</code> 3377</code></pre><h3>Creating First Seed</h3><p>Suppose we want to insert some data into a few tables by default. If we follow up on previous example we can consider creating a demo user for <code>User</code> table.</p><p>To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.</p><p>Let's create a seed file which will add a demo user to our <code>User</code> table.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize seed:generate --name demo-user</code> 3378</code></pre><p>This command will create a seed file in <code>seeders</code> folder. File name will look something like <code>XXXXXXXXXXXXXX-demo-user.js</code>. It follows the same <code>up / down</code> semantics as the migration files.</p><p>Now we should edit this file to insert demo user to <code>User</code> table.</p><pre><code class="lang-js"><code class="source-code prettyprint">'use strict'; 3379 3380module.exports = { 3381 up: (queryInterface, Sequelize) => { 3382 return queryInterface.bulkInsert('Users', [{ 3383 firstName: 'John', 3384 lastName: 'Doe', 3385 email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9dddcd4d6f9dddcd4d697dad6d4">[email protected]</a>' 3386 }], {}); 3387 }, 3388 3389 down: (queryInterface, Sequelize) => { 3390 return queryInterface.bulkDelete('Users', null, {}); 3391 } 3392};</code> 3393</code></pre><h3>Running Seeds</h3><p>In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple c
3393ommand.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize db:seed:all</code> 3394</code></pre><p>This will execute that seed file and you will have a demo user inserted into <code>User</code> table.</p><p><strong>Note:</strong> <em>Seeders execution is not stored anywhere unlike migrations, which use the <code>SequelizeMeta</code> table. If you wish to override this please read <code>Storage</code> section</em></p><h3>Undoing Seeds</h3><p>Seeders can be undone if they are using any storage. There are two commands available for that:</p><p>If you wish to undo most recent seed</p><pre><code class="lang-bash"><code class="source-code prettyprint">node_modules/.bin/sequelize db:seed:undo</code> 3395</code></pre><p>If you wish to undo all seeds</p><pre><code class="lang-bash"><code class="source-code prettyprint">node_modules/.bin/sequelize db:seed:undo:all</code> 3396</code></pre><h2>Advance Topics</h2><h3>Migration Skeleton</h3><p>The following skeleton shows a typical migration file.</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = { 3397 up: (queryInterface, Sequelize) => { 3398 // logic for transforming into the new state 3399 }, 3400 3401 down: (queryInterface, Sequelize) => { 3402 // logic for reverting the changes 3403 } 3404}</code> 3405</code></pre><p>The passed <code>queryInterface</code> object can be used to modify the database. The <code>Sequelize</code> object stores the available data types such as <code>STRING</code> or <code>INTEGER</code>. Function <code>up</code> or <code>down</code> should return a <code>Promise</code>. Let's look at an example:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = { 3406 up: (queryInterface, Sequelize) => { 3407 return queryInterface.createTable('Person', { 3408 name: Sequelize.STRING, 3409 isBetaMember: { 3410 type: Sequelize.BOOLEAN, 3411 defaultValue: false, 3412 allowNull: false 3413 } 3414 }); 3415 }, 3416 down: (queryInterface, Sequelize) => { 3417 return queryInterface.dropTable('Person'); 3418 } 3419}</code> 3420</code></pre><h3>The <code>.sequelizerc</code> File</h3><p>This is a special configuration file. It lets you specify various options that you would usually pass as arguments to CLI. Some scenarios where you can use it.</p><ul> 3421<li>You want to override default path to <code>migrations</code>, <code>models</code>, <code>seeders</code> or <code>config</code> folder.</li> 3422<li>You want to rename <code>config.json</code> to something else like <code>database.json</code></li> 3423</ul><p>And a whole lot more. Let's see how you can use this file for custom configuration.</p><p>For starters, let's create an empty file in root directory of your project.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ touch .sequelizerc</code> 3424</code></pre><p>Now let's work with an example config.</p><pre><code class="lang-js"><code class="source-code prettyprint">const path = require('path'); 3425 3426module.exports = { 3427 'config': path.resolve('config', 'database.json'), 3428 'models-path': path.resolve('db', 'models'), 3429 'seeders-path': path.resolve('db', 'seeders'), 3430 'migrations-path': path.resolve('db', 'migrations') 3431}</code> 3432</code></pre><p>With this config you are telling CLI to</p><ul> 3433<li>Use <code>config/database.json</code> file for config settings</li> 3434<li>Use <code>db/models</code> as models folder</li> 3435<li>Use <code>db/seeders</code> as seeders folder</li> 3436<li>Use <code>db/migrations</code> as migrations folder</li> 3437</ul><h3>Dynamic Configuration</h3><p>Configuration file is by default a JSON file called <code>config.json</code>. But sometimes you want to execute some code or access environment variables which is not possible in JSON files.</p><p>Sequelize CLI can read from both <code>JSON</code> and <code>JS</code> files. This can be setup with <code>.sequelizerc</code> file. Let see how</p><p>First you need to create a <code>.sequelizerc</code> file in root folder of your project. This file should override config path to a <code>JS</code> file. Like this</p><pre><code class="lang-js"><code class="source-code prettyprint">const path = require('path'); 3438 3439module.exports = {
3440 'config': path.resolve('config', 'config.js') 3441}</code> 3442</code></pre><p>Now Sequelize CLI will load <code>config/config.js</code> for getting configuration options. Since this is a JS file you can have any code executed and export final dynamic configuration file.</p><p>An example of <code>config/config.js</code> file</p><pre><code class="lang-js"><code class="source-code prettyprint">const fs = require('fs'); 3443 3444module.exports = { 3445 development: { 3446 username: 'database_dev', 3447 password: 'database_dev', 3448 database: 'database_dev', 3449 host: '127.0.0.1', 3450 dialect: 'mysql' 3451 }, 3452 test: { 3453 username: 'database_test', 3454 password: null, 3455 database: 'database_test', 3456 host: '127.0.0.1', 3457 dialect: 'mysql' 3458 }, 3459 production: { 3460 username: process.env.DB_USERNAME, 3461 password: process.env.DB_PASSWORD, 3462 database: process.env.DB_NAME, 3463 host: process.env.DB_HOSTNAME, 3464 dialect: 'mysql', 3465 dialectOptions: { 3466 ssl: { 3467 ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt') 3468 } 3469 } 3470 } 3471};</code> 3472</code></pre><h3>Using Environment Variables</h3><p>With CLI you can directly access the environment variables inside the <code>config/config.js</code>. You can use <code>.sequelizerc</code> to tell CLI to use <code>config/config.js</code> for configuration. This is explained in last section.</p><p>Then you can just expose file with proper environment variables.</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = { 3473 development: { 3474 username: 'database_dev', 3475 password: 'database_dev', 3476 database: 'database_dev', 3477 host: '127.0.0.1', 3478 dialect: 'mysql' 3479 }, 3480 test: { 3481 username: process.env.CI_DB_USERNAME, 3482 password: process.env.CI_DB_PASSWORD, 3483 database: process.env.CI_DB_NAME, 3484 host: '127.0.0.1', 3485 dialect: 'mysql' 3486 }, 3487 production: { 3488 username: process.env.PROD_DB_USERNAME, 3489 password: process.env.PROD_DB_PASSWORD, 3490 database: process.env.PROD_DB_NAME, 3491 host: process.env.PROD_DB_HOSTNAME, 3492 dialect: 'mysql' 3493 }</code> 3494</code></pre><h3>Specifying Dialect Options</h3><p>Sometime you want to specify a dialectOption, if it's a general config you can just add it in <code>config/config.json</code>. Sometime you want to execute some code to get dialectOptions, you should use dynamic config file for those cases.</p><pre><code class="lang-json"><code class="source-code prettyprint">{ 3495 "production": { 3496 "dialect":"mysql", 3497 "dialectOptions": { 3498 "bigNumberStrings": true 3499 } 3500 } 3501}</code> 3502</code></pre><h3>Production Usages</h3><p>Some tips around using CLI and migration setup in production environment.</p><p>1) Use environment variables for config settings. This is better achieved with dynamic configuration. A sample production safe configuration may look like.</p><pre><code class="lang-js"><code class="source-code prettyprint">const fs = require('fs'); 3503 3504module.exports = { 3505 development: { 3506 username: 'database_dev', 3507 password: 'database_dev', 3508 database: 'database_dev', 3509 host: '127.0.0.1', 3510 dialect: 'mysql' 3511 }, 3512 test: { 3513 username: 'database_test', 3514 password: null, 3515 database: 'database_test', 3516 host: '127.0.0.1', 3517 dialect: 'mysql' 3518 }, 3519 production: { 3520 username: process.env.DB_USERNAME, 3521 password: process.env.DB_PASSWORD, 3522 database: process.env.DB_NAME, 3523 host: process.env.DB_HOSTNAME, 3524 dialect: 'mysql', 3525 dialectOptions: { 3526 ssl: { 3527 ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt') 3528 } 3529 } 3530 } 3531};</code> 3532</code></pre><p>Our goal is to use environment variables for various database secrets and not accidentally check them in to source control.</p><h3>Storage</h3><p>There are three types of storage that you can use: <code>sequelize</code>, <code>json</code>, and <code>none</code>.</p><ul> 3533<li><code>sequelize</code> : stores migrations and seeds in a table on the sequelize database</li> 3534<li><code>json</code> : stores migrations and seeds on a json file</li> 3535<li><code>none</code> : does not store any migration/seed</li> 3536</ul><h4>Migration Storage</h4><p>By default the CLI will create a table in your database called <code>SequelizeMeta</code> containing an entry 3537for each executed migration. To change this behavior, there are three options you can add to the 3538configuration file. Using <code>migrationStorage</code>, you can choose the type of storage to be used for 3539migrations. If you choose <code>json</code>, you can specify the path of the file using <code>migrationStoragePath</code> 3540or the CLI will write to the file <code>sequelize-meta.json</code>. If you want to keep the information in the 3541database, using <code>sequelize</code>, but want to use a different table, you can change the table name using 3542<code>migrationStorageTableName</code>.</p><pre><code class="lang-json"><code class="source-code prettyprint">{ 3543 "development": { 3544 "username": "root", 3545 "password": null, 3546 "database": "database_development", 3547 "host": "127.0.0.1", 3548 "dialect": "mysql", 3549 3550 // Use a different storage type. Default: sequelize 3551 "migrationStorage": "json", 3552 3553 // Use a different file name. Default: sequelize-meta.json 3554 "migrationStoragePath": "sequelizeMeta.json", 3555 3556 // Use a different table name. Default: SequelizeMeta 3557 "migrationStorageTableName": "sequelize_meta" 3558 } 3559}</code> 3560</code></pre><p><strong>Note:</strong> <em>The <code>none</code> storage is not recommended as a migration storage. If you decide to use it, be 3561aware of the implications of having no record of what migrations did or didn't run.</em></p><h4>Seed Storage</h4><p>By default the CLI will not save any seed that is executed. If you choose to change this behavior (!), 3562you can use <code>seederStorage</code> in the configuration file to change the storage type. If you choose <code>json</code>, 3563you can specify the path of the file using <code>seederStoragePath</code> or the CLI will write to the file 3564<code>sequelize-data.json</code>. If you want to keep the information in the database, using <code>sequelize</code>, you can 3565specify the table name using <code>seederStorageTableName</code>, or it will default to <code>SequelizeData</code>.</p><pre><code class="lang-json"><code class="source-code prettyprint">{ 3566 "development": { 3567 "username": "root", 3568 "password": null, 3569 "database": "database_development", 3570 "host": "127.0.0.1", 3571 "dialect": "mysql", 3572 // Use a different storage. Default: none 3573 "seederStorage": "json", 3574 // Use a different file name. Default: sequelize-data.json 3575 "seederStoragePath": "sequelizeData.json", 3576 // Use a different table name. Default: SequelizeData 3577 "seederStorageTableName": "sequelize_data" 3578 } 3579}</code> 3580</code></pre><h3>Configuration Connection String</h3><p>As an alternative to the <code>--config</code> option with configuration files defining your database, you can 3581use the <code>--url</code> option to pass in a connection string. For example:</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ node_modules/.bin/sequelize db:migrate --url 'mysql://root:password@mysql_host.com/database_name'</code> 3582</code></pre><h3>Connecting over SSL</h3><p>Ensure ssl is specified in both <code>dialectOptions</code> and in the base config.</p><pre><code class="lang-json"><code class="source-code prettyprint">{ 3583 "production": { 3584 "dialect":"postgres", 3585 "ssl": true, 3586 "dialectOptions": { 3587 "ssl": true 3588 } 3589 } 3590}</code> 3591</code></pre><h3>Programmatic use</h3><p>Sequelize has a <a href="https://github.com/sequelize/umzug">sister library</a> for programmatically handling execution and logging of migration tasks.</p><h2>Query Interface</h2><p>Using <code>queryInterface</code> object described before you can change database schema. To see full list of public methods it supports check <a href='/v4/class/lib/query-interface.js~queryinterface'>QueryInterface API</a></p></div> 3592 <a data-ice='link' href='/v4/manual/tutorial/migrations'></a> 3593 </div> 3594 </div> 3595<div class="manual-card-wrap" data-ice="cards"> 3596 <h1 data-ice="label" class="manual-color manual-color-tutorial" data-section-count="â â â "><span data-ice="label-inner">Upgrade to V4</span></h1> 3597 <div class="manual-card"> 3598 <div data-ice="card"><h1>Upgrade to V4</h1><p>Sequelize v4 is the current release and it introduces some breaking changes. Majority of sequelize codebase has been refactored to use ES2015 features. The following guide lists s
3598ome of the changes to upgrade from v3 to v4.</p><h2>Changelog</h2><p>Full <a href="https://github.com/sequelize/sequelize/blob/b49f936e9aa316cf4a13bade76585acf4d5d8b04/changelog.md">Changelog</a> for v4 release.</p><h2>Breaking Changes</h2><h3>Node</h3><p>To use new ES2015 features, Sequelize v4 requires at least Node v4 or above.</p><h3>General</h3><ul> 3599<li>Counter Cache plugin and consequently the <code>counterCache</code> option for associations has been removed.</li> 3600<li>MariaDB dialect now removed. This was just a thin wrapper around MySQL. You can set <code>dialect: 'mysql'</code> an d Sequelize should be able to work with MariaDB server.</li> 3601<li><code>Model.Instance</code> and <code>instance.Model</code> are removed. To access the Model from an instance, simply use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"><code>instance.constructor</code></a>. The Instance class (<code>Model.Instance</code>) is now the Model itself.</li> 3602<li>Sequelize now uses an independent copy of bluebird library.</li> 3603<li>Promises returned by sequelize are now instances of <code>Sequelize.Promise</code> instead of global bluebird <code>Promise</code>.</li> 3604<li>Pooling library was updated to <code>v3</code>, now you will need to call <code>sequelize.close()</code> to shutdown the pool.</li> 3605</ul><h3>Config / Options</h3><ul> 3606<li><p>Removed support for old connection pooling configuration keys. Instead of</p> 3607<p><strong>Old</strong></p> 3608<pre><code class="lang-js"><code class="source-code prettyprint"> pool: { 3609 maxIdleTime: 30000, 3610 minConnections: 20, 3611 maxConnections: 30 3612 }</code> 3613</code></pre> 3614<p><strong>New</strong></p> 3615<pre><code class="lang-js"><code class="source-code prettyprint"> pool: { 3616 idle: 30000, 3617 min: 20, 3618 max: 30 3619 }</code> 3620</code></pre> 3621</li> 3622<li>Removed support for <code>pool: false</code>. To use a single connection, set <code>pool.max</code> to 1.</li> 3623<li>Removed support for <code>referencesKey</code>, use a references object<pre><code class="lang-js"><code class="source-code prettyprint"> references: { 3624 key: '', 3625 model: '' 3626 }</code> 3627</code></pre> 3628</li> 3629<li><p>Removed <code>classMethods</code> and <code>instanceMethods</code> options from <code>sequelize.define</code>. Sequelize models 3630are now ES6 classes. You can set class / instance level methods like this</p> 3631<p><strong>Old</strong></p> 3632<pre><code class="lang-js"><code class="source-code prettyprint">const Model = sequelize.define('Model', { 3633 ... 3634}, { 3635 classMethods: { 3636 associate: function (model) {...} 3637 }, 3638 instanceMethods: { 3639 someMethod: function () { ...} 3640 } 3641});</code> 3642</code></pre> 3643<p><strong>New</strong></p> 3644<pre><code class="lang-js"><code class="source-code prettyprint">const Model = sequelize.define('Model', { 3645 ... 3646}); 3647 3648// Class Method 3649Model.associate = function (models) { 3650 ...associate the models 3651}; 3652 3653// Instance Method 3654Model.prototype.someMethod = function () {..}</code> 3655</code></pre> 3656</li> 3657<li><p><code>options.order</code> now only accepts values with type of array or Sequelize method. Support for string values (ie <code>{order: 'name DESC'}</code>) has been deprecated.</p> 3658</li> 3659<li>With <code>BelongsToMany</code> relationships <code>add/set/create</code> setters now set through attributes by passing them as <code>options.through</code> (previously second argument was used as through attributes, now it's considered options with <code>through</code> being a sub option)</li> 3660<li><p>Raw options for where, order and group like <code>where: { $raw: '..', order: [{ raw: '..' }], group: [{ raw: '..' }] }</code> have been removed to prevent SQL injection attacks.</p> 3661<p><strong>Old</strong></p> 3662<pre><code class="lang-js"><code class="source-code prettyprint">user.addProject(project, { status: 'started' });</code> 3663</code></pre> 3664<p><strong>New</strong></p> 3665<pre><code class="lang-js"><code class="source-code prettyprint">user.addProject(project, { through: { status: 'started' } });</code> 3666</code></pre> 3667</li> 3668</ul><h3>Data Types</h3><ul> 3669<li>(MySQL/Postgres) <code>BIGINT</code> now returned as string.</li> 3670<li>(MySQL/Postgres) <code>DECIMAL</code> and <code>NEWDECIMAL</code> types now returned as string.</li> 3671<li>(MSSQL) <code>DataTypes.DATE</code> now uses <code>DATETIMEOFFSET</code> instead of <code>DATETIME2</code> sql datatype in case of MSSQL to record timezone. To migrate existing <code>DATETIME2</code> columns into <code>DATETIMEOFFSET</code>, see <a href="https://github.com/sequelize/sequelize/pull/7201#issuecomment-278899803">#7201</a>.</li> 3672<li><code>DATEONLY</code> now returns string in <code>YYYY-MM-DD</code> format rather than <code>Date</code> type</li> 3673</ul><h3>Transactions / CLS</h3><ul> 3674<li>Removed <code>autocommit: true</code> default, set this option explicitly to have transactions auto commit.</li> 3675<li>Removed default <code>REPEATABLE_READ</code> transaction isolation. The isolation level now defaults to that of the database. Explicitly pass the required isolation level when initiating the transaction.</li> 3676<li><p>The CLS patch does not affect global bluebird promise. Transaction will not automatically get passed to methods when used with <code>Promise.all</code> and other bluebird methods. Explicitly patch your bluebird instance to get CLS to work with bluebird methods.</p> 3677<pre><code class="lang-bash"><code class="source-code prettyprint"> $ npm install --save cls-bluebird</code> 3678</code></pre> 3679<pre><code class="lang-js"><code class="source-code prettyprint"> const Sequelize = require('sequelize'); 3680 const Promise = require('bluebird'); 3681 const clsBluebird = require('cls-bluebird'); 3682 const cls = require('continuation-local-storage'); 3683 3684 const ns = cls.createNamespace('transaction-namespace'); 3685 clsBluebird(ns, Promise); 3686 3687 Sequelize.useCLS(ns);</code> 3688</code></pre> 3689</li> 3690</ul><h3>Raw Queries</h3><ul> 3691<li>Sequelize now supports bind parameters for all dialects. In v3 <code>bind</code> option would fallback to <code>replacements</code> if dialect didn't supported binding. This could be a breaking change for MySQL / MSSQL where now queries will actually use bind parameters instead of replacements fallback.</li> 3692</ul><h3>Others</h3><ul> 3693<li><code>Sequelize.Validator</code> is now an independent copy of <code>validator</code> library.</li> 3694<li><code>Model.validate</code> instance method now runs validation hooks by default. Previously you needed to pass <code>{ hooks: true }</code>
3694. You can override this behavior by passing <code>{ hooks: false }</code>.</li> 3695<li>The resulting promise from the <code>Model.validate</code> instance method will be rejected when validation fails. It will fulfill when validation succeeds.</li> 3696<li><code>Sequelize.Utils</code> is not longer part of the public API, use it at your own risk.</li> 3697<li><code>Hooks</code> should return Promises now. Callbacks are deprecated.</li> 3698<li>Getters wont run with <code>instance.get({ raw: true })</code>, use <code>instance.get({ plain: true })</code></li> 3699<li><p><code>required</code> inside include does not propagate up the include chain.</p> 3700<p>To get v3 compatible results you'll need to either set <code>required</code> on the containing include.</p> 3701<p><strong>Old</strong></p> 3702<pre><code class="lang-js"><code class="source-code prettyprint">user.findOne({ 3703 include: { 3704 model: project, 3705 include: { 3706 model: task, 3707 required: true 3708 } 3709 } 3710});</code> 3711</code></pre> 3712<p><strong>New</strong></p> 3713<pre><code class="lang-js"><code class="source-code prettyprint">User.findOne({ 3714 include: { 3715 model: Project, 3716 required: true, 3717 include: { 3718 model: Task, 3719 required: true 3720 } 3721 } 3722}); 3723 3724User.findOne({ 3725 include: { 3726 model: Project, 3727 required: true, 3728 include: { 3729 model: Task, 3730 where: { type: 'important' } //where cause required to default to true 3731 } 3732 } 3733});</code> 3734</code></pre> 3735<p>Optionally you can add a <code>beforeFind</code> hook to get v3 compatible behavior -</p> 3736<pre><code class="lang-js"><code class="source-code prettyprint">function propagateRequired(modelDescriptor) { 3737 let include = modelDescriptor.include; 3738 3739 if (!include) return false; 3740 if (!Array.isArray(include)) include = [include]; 3741 3742 return include.reduce((isRequired, descriptor) => { 3743 const hasRequiredChild = propogateRequired(descriptor); 3744 if ((descriptor.where || hasRequiredChild) && descriptor.required === undefined) { 3745 descriptor.required = true; 3746 } 3747 return descriptor.required || isRequired; 3748 }, false); 3749} 3750 3751const sequelize = new Sequelize(..., { 3752 ..., 3753 define: { 3754 hooks: { 3755 beforeFind: propagateRequired 3756 } 3757 } 3758});</code> 3759</code></pre> 3760</li> 3761</ul></div> 3762 <a data-ice='link' href='/v4/manual/tutorial/upgrade-to-v4'></a> 3763 </div> 3764 </div> 3765<div class="manual-card-wrap" data-ice="cards"> 3766 <h1 data-ice="label" class="manual-color manual-color-advanced" data-section-count="â â "><span data-ice="label-inner">Working with legacy tables</span></h1> 3767 <div class="manual-card"> 3768 <div data-ice="card"><h1>Working with legacy tables</h1><p>While out of the box Sequelize will seem a bit opinionated it's trivial to both legacy and forward proof your application by defining (otherwise generated) table and field names.</p><h2>Tables</h2><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.define('user', { 3769 3770}, { 3771 tableName: 'users' 3772});</code> 3773</code></pre><h2>Fields</h2><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.define('modelName', { 3774 userId: { 3775 type: Sequelize.INTEGER, 3776 field: 'user_id' 3777 } 3778});</code> 3779</code></pre><h2>Primary keys</h2><p>Sequelize will assume your table has a <code>id</code> primary key property by default.</p><p>To define your own primary key:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.define('collection', { 3780 uid: { 3781 type: Sequelize.INTEGER, 3782 primaryKey: true, 3783 autoIncrement: true // Automatically gets converted to SERIAL for postgres 3784 } 3785}); 3786 3787sequelize.define('collection', { 3788 uuid: { 3789 type: Sequelize.UUID, 3790 primaryKey: true 3791 } 3792});</code> 3793</code></pre><p>And if your model has no primary key at all you can use <code>Model.removeAttribute('id');</code></p><h2>Foreign keys</h2><pre><code class="lang-js"><code class="source-code prettyprint">// 1:1 3794Organization.belongsTo(User, {foreignKey: 'owner_id'}); 3795User.hasOne(Organization, {foreignKey: 'owner_id'}); 3796 3797// 1:M 3798Project.hasMany(Task, {foreignKey: 'tasks_pk'}); 3799Task.belongsTo(Project, {foreignKey: 'tasks_pk'}); 3800 3801// N:M 3802User.hasMany(Role, {through: 'user_has_roles', foreignKey: 'user_role_user_id'}); 3803Role.hasMany(User, {through: 'user_has_roles', foreignKey: 'roles_identifier'});</code> 3804</code></pre></div> 3805 <a data-ice='link' href='/v4/manual/advanced/legacy'></a> 3806 </div> 3807 </div> 3808<div class="manual-card-wrap" data-ice="cards"> 3809 <h1 data-ice="label" class="manual-color manual-color-reference" data-section-count="â â â â â "><span data-ice="label-inner">References</span></h1> 3810 <div class="manual-card"> 3811 <div data-ice="card"><h1>References</h1> 3812<div data-ice="classSummary"><h2 id="class">Class Summary</h2><table class="summary" data-ice="summary"> 3813 <thead><tr><td data-ice="title" colspan="3">Static Public Class Summary</td></tr></thead> 3814 <tbody> 3815 3816 <tr data-ice="target"> 3817 <td>
3818 <span class="access" data-ice="access">public</span> 3819 3820 3821 3822 <span class="override" data-ice="override"></span> 3823 </td> 3824 <td> 3825 <div> 3826 <p> 3827 3828 3829 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~accessdeniederror'>AccessDeniedError</a></span></span> 3830 </p> 3831 </div> 3832 <div> 3833 3834 3835 <div data-ice="description"><p>Thrown when a connection to a database is refused due to insufficient privileges</p> 3836</div> 3837 </div> 3838 </td> 3839 <td> 3840 3841 3842 </td> 3843 </tr> 3844<tr data-ice="target"> 3845 <td> 3846 <span class="access" data-ice="access">public</span> 3847 3848 3849 3850 <span class="override" data-ice="override"></span> 3851 </td> 3852 <td> 3853 <div> 3854 <p> 3855 3856 3857 <span data-ice="name"><span><a href='/v4/class/lib/associations/base.js~association'>Association</a></span></span> 3858 </p> 3859 </div> 3860 <div> 3861 3862 3863 <div data-ice="description"><p>Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).</p> 3864</div> 3865 </div> 3866 </td> 3867 <td> 3868 3869 3870 </td> 3871 </tr> 3872<tr data-ice="target"> 3873 <td> 3874 <span class="access" data-ice="access">public</span> 3875 3876 3877 3878 <span class="override" data-ice="override"></span> 3879 </td> 3880 <td> 3881 <div> 3882 <p> 3883 3884 3885 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~associationerror'>AssociationError</a></span></span> 3886 </p> 3887 </div> 3888 <div> 3889 3890 3891 <div data-ice="description"><p>Thrown when an association is improperly constructed (see message for details)</p> 3892</div> 3893 </div> 3894 </td> 3895 <td> 3896 3897 3898 </td> 3899 </tr> 3900<tr data-ice="target"> 3901 <td> 3902 <span class="access" data-ice="access">public</span> 3903 3904 3905 3906 <span class="override" data-ice="override"></span> 3907 </td> 3908 <td> 3909 <div> 3910 <p> 3911 3912 3913 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~baseerror'>BaseError</a></span></span> 3914 </p> 3915 </div> 3916 <div> 3917 3918 3919 <div data-ice="description"><p>Sequelize provides a host of custom error classes, to allow you to do easier debugging.</p> 3920</div> 3921 </div> 3922 </td> 3923 <td> 3924 3925 3926 </td> 3927 </tr> 3928<tr data-ice="target"> 3929 <td> 3930 <span class="access" data-ice="access">public</span> 3931 3932 3933 3934 <span class="override" data-ice="override"></span> 3935 </td> 3936 <td> 3937 <div> 3938 <p> 3939 3940 3941 <span data-ice="name"><span><a href='/v4/class/lib/associations/belongs-to.js~belongsto'>BelongsTo</a></span></span> 3942 </p> 3943 </div> 3944 <div> 3945 3946 3947 <div data-ice="description"><p>One-to-one association</p> 3948</div> 3949 </div> 3950 </td> 3951 <td> 3952 3953 3954 </td> 3955 </tr> 3956<tr data-ice="target"> 3957 <td> 3958 <span class="access" data-ice="access">public</span> 3959 3960 3961 3962 <span class="override" data-ice="override"></span> 3963 </td> 3964 <td> 3965 <div> 3966 <p> 3967 3968 3969 <span data-ice="name"><span><a href='/v4/class/lib/associations/belongs-to-many.js~belongstomany'>BelongsToMany</a></span></span> 3970 </p> 3971 </div> 3972 <div> 3973 3974 3975 <div data-ice="description"><p>Many-to-many association with a join table.</p> 3976</div> 3977 </div> 3978 </td> 3979 <td> 3980 3981 3982 </td> 3983 </tr> 3984<tr data-ice="target"> 3985 <td> 3986 <span class="access" data-ice="access">public</span> 3987 3988 3989 3990 <span class="override" data-ice="override"></span> 3991 </td> 3992 <td> 3993 <div> 3994 <p> 3995 3996 3997 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~bulkrecorderror'>BulkRecordError</a></span></span><span data-ice="signature">(error: <span>Error</span>, record: <span>Object</span>)</span> 3998 </p> 3999 </div> 4000 <div> 4001 4002 4003 <div data-ice="description"><p>Thrown when bulk operation fails, it represent per record level error.</p> 4004</div> 4005 </div> 4006 </td> 4007 <td> 4008 4009 4010 </td> 4011 </tr> 4012<tr data-ice="target"> 4013 <td>
4014 <span class="access" data-ice="access">public</span> 4015 4016 4017 4018 <span class="override" data-ice="override"></span> 4019 </td> 4020 <td> 4021 <div> 4022 <p> 4023 4024 4025 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~connectionerror'>ConnectionError</a></span></span> 4026 </p> 4027 </div> 4028 <div> 4029 4030 4031 <div data-ice="description"><p>A base class for all connection related errors.</p> 4032</div> 4033 </div> 4034 </td> 4035 <td> 4036 4037 4038 </td> 4039 </tr> 4040<tr data-ice="target"> 4041 <td> 4042 <span class="access" data-ice="access">public</span> 4043 4044 4045 4046 <span class="override" data-ice="override"></span> 4047 </td> 4048 <td> 4049 <div> 4050 <p> 4051 4052 4053 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~connectionrefusederror'>ConnectionRefusedError</a></span></span> 4054 </p> 4055 </div> 4056 <div> 4057 4058 4059 <div data-ice="description"><p>Thrown when a connection to a database is refused</p> 4060</div> 4061 </div> 4062 </td> 4063 <td> 4064 4065 4066 </td> 4067 </tr> 4068<tr data-ice="target"> 4069 <td> 4070 <span class="access" data-ice="access">public</span> 4071 4072 4073 4074 <span class="override" data-ice="override"></span> 4075 </td> 4076 <td> 4077 <div> 4078 <p> 4079 4080 4081 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~connectiontimedouterror'>ConnectionTimedOutError</a></span></span> 4082 </p> 4083 </div> 4084 <div> 4085 4086 4087 <div data-ice="description"><p>Thrown when a connection to a database times out</p> 4088</div> 4089 </div> 4090 </td> 4091 <td> 4092 4093 4094 </td> 4095 </tr> 4096<tr data-ice="target"> 4097 <td> 4098 <span class="access" data-ice="access">public</span> 4099 4100 4101 4102 <span class="override" data-ice="override"></span> 4103 </td> 4104 <td> 4105 <div> 4106 <p> 4107 4108 4109 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~databaseerror'>DatabaseError</a></span></span> 4110 </p> 4111 </div> 4112 <div> 4113 4114 4115 <div data-ice="description"><p>A base class for all database related errors.</p> 4116</div> 4117 </div> 4118 </td> 4119 <td> 4120 4121 4122 </td> 4123 </tr> 4124<tr data-ice="target"> 4125 <td> 4126 <span class="access" data-ice="access">public</span> 4127 4128 4129 4130 <span class="override" data-ice="override"></span> 4131 </td> 4132 <td> 4133 <div> 4134 <p> 4135 4136 4137 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~eagerloadingerror'>EagerLoadingError</a></span></span> 4138 </p> 4139 </div> 4140 <div> 4141 4142 4143 <div data-ice="description"><p>Thrown when an include statement is improperly constructed (see message for details)</p> 4144</div> 4145 </div> 4146 </td> 4147 <td> 4148 4149 4150 </td> 4151 </tr> 4152<tr data-ice="target"> 4153 <td> 4154 <span class="access" data-ice="access">public</span> 4155 4156 4157 4158 <span class="override" data-ice="override"></span> 4159 </td> 4160 <td> 4161 <div> 4162 <p> 4163 4164 4165 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~emptyresulterror'>EmptyResultError</a></span></span> 4166 </p> 4167 </div> 4168 <div> 4169 4170 4171 <div data-ice="description"><p>Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)</p> 4172</div> 4173 </div> 4174 </td> 4175 <td> 4176 4177 4178 </td> 4179 </tr> 4180<tr data-ice="target"> 4181 <td> 4182 <span class="access" data-ice="access">public</span> 4183 4184 4185 4186 <span class="override" data-ice="override"></span> 4187 </td> 4188 <td> 4189 <div> 4190 <p> 4191 4192 4193 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~exclusionconstrainterror'>ExclusionConstraintError</a></span></span> 4194 </p> 4195 </div> 4196 <div> 4197 4198 4199 <div data-ice="description"><p>Thrown when an exclusion constraint is violated in the database</p> 4200</div> 4201 </div> 4202 </td> 4203 <td> 4204 4205 4206 </td> 4207 </tr> 4208<tr data-ice="target"> 4209 <td>
4210 <span class="access" data-ice="access">public</span> 4211 4212 4213 4214 <span class="override" data-ice="override"></span> 4215 </td> 4216 <td> 4217 <div> 4218 <p> 4219 4220 4221 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~foreignkeyconstrainterror'>ForeignKeyConstraintError</a></span></span> 4222 </p> 4223 </div> 4224 <div> 4225 4226 4227 <div data-ice="description"><p>Thrown when a foreign key constraint is violated in the database</p> 4228</div> 4229 </div> 4230 </td> 4231 <td> 4232 4233 4234 </td> 4235 </tr> 4236<tr data-ice="target"> 4237 <td> 4238 <span class="access" data-ice="access">public</span> 4239 4240 4241 4242 <span class="override" data-ice="override"></span> 4243 </td> 4244 <td> 4245 <div> 4246 <p> 4247 4248 4249 <span data-ice="name"><span><a href='/v4/class/lib/associations/has-many.js~hasmany'>HasMany</a></span></span> 4250 </p> 4251 </div> 4252 <div> 4253 4254 4255 <div data-ice="description"><p>One-to-many association</p> 4256</div> 4257 </div> 4258 </td> 4259 <td> 4260 4261 4262 </td> 4263 </tr> 4264<tr data-ice="target"> 4265 <td> 4266 <span class="access" data-ice="access">public</span> 4267 4268 4269 4270 <span class="override" data-ice="override"></span> 4271 </td> 4272 <td> 4273 <div> 4274 <p> 4275 4276 4277 <span data-ice="name"><span><a href='/v4/class/lib/associations/has-one.js~hasone'>HasOne</a></span></span> 4278 </p> 4279 </div> 4280 <div> 4281 4282 4283 <div data-ice="description"><p>One-to-one association</p> 4284</div> 4285 </div> 4286 </td> 4287 <td> 4288 4289 4290 </td> 4291 </tr> 4292<tr data-ice="target"> 4293 <td> 4294 <span class="access" data-ice="access">public</span> 4295 4296 4297 4298 <span class="override" data-ice="override"></span> 4299 </td> 4300 <td> 4301 <div> 4302 <p> 4303 4304 4305 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~hostnotfounderror'>HostNotFoundError</a></span></span> 4306 </p> 4307 </div> 4308 <div> 4309 4310 4311 <div data-ice="description"><p>Thrown when a connection to a database has a hostname that was not found</p> 4312</div> 4313 </div> 4314 </td> 4315 <td> 4316 4317 4318 </td> 4319 </tr> 4320<tr data-ice="target"> 4321 <td> 4322 <span class="access" data-ice="access">public</span> 4323 4324 4325 4326 <span class="override" data-ice="override"></span> 4327 </td> 4328 <td> 4329 <div> 4330 <p> 4331 4332 4333 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~hostnotreachableerror'>HostNotReachableError</a></span></span> 4334 </p> 4335 </div> 4336 <div> 4337 4338 4339 <div data-ice="description"><p>Thrown when a connection to a database has a hostname that was not reachable</p> 4340</div> 4341 </div> 4342 </td> 4343 <td> 4344 4345 4346 </td> 4347 </tr> 4348<tr data-ice="target"> 4349 <td> 4350 <span class="access" data-ice="access">public</span> 4351 4352 4353 4354 <span class="override" data-ice="override"></span> 4355 </td> 4356 <td> 4357 <div> 4358 <p> 4359 4360 4361 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~instanceerror'>InstanceError</a></span></span> 4362 </p> 4363 </div> 4364 <div> 4365 4366 4367 <div data-ice="description"><p>Thrown when a some problem occurred with Instance methods (see message for details)</p> 4368</div> 4369 </div> 4370 </td> 4371 <td> 4372 4373 4374 </td> 4375 </tr> 4376<tr data-ice="target"> 4377 <td> 4378 <span class="access" data-ice="access">public</span> 4379 4380 4381 4382 <span class="override" data-ice="override"></span> 4383 </td> 4384 <td> 4385 <div> 4386 <p> 4387 4388 4389 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~invalidconnectionerror'>InvalidConnectionError</a></span></span> 4390 </p> 4391 </div> 4392 <div> 4393 4394 4395 <div data-ice="description"><p>Thrown when a connection to a database has invalid values for any of the connection parameters</p> 4396</div> 4397 </div> 4398 </td> 4399 <td> 4400 4401 4402 </td> 4403 </tr> 4404<tr data-ice="target"> 4405 <td>
4406 <span class="access" data-ice="access">public</span> 4407 4408 4409 4410 <span class="override" data-ice="override"></span> 4411 </td> 4412 <td> 4413 <div> 4414 <p> 4415 4416 4417 <span data-ice="name"><span><a href='/v4/class/lib/model.js~model'>Model</a></span></span> 4418 </p> 4419 </div> 4420 <div> 4421 4422 4423 <div data-ice="description"><p>A Model represents a table in the database.</p> 4424</div> 4425 </div> 4426 </td> 4427 <td> 4428 4429 4430 </td> 4431 </tr> 4432<tr data-ice="target"> 4433 <td> 4434 <span class="access" data-ice="access">public</span> 4435 4436 4437 4438 <span class="override" data-ice="override"></span> 4439 </td> 4440 <td> 4441 <div> 4442 <p> 4443 4444 4445 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~optimisticlockerror'>OptimisticLockError</a></span></span> 4446 </p> 4447 </div> 4448 <div> 4449 4450 4451 <div data-ice="description"><p>Thrown when attempting to update a stale model instance</p> 4452</div> 4453 </div> 4454 </td> 4455 <td> 4456 4457 4458 </td> 4459 </tr> 4460<tr data-ice="target"> 4461 <td> 4462 <span class="access" data-ice="access">public</span> 4463 4464 4465 4466 <span class="override" data-ice="override"></span> 4467 </td> 4468 <td> 4469 <div> 4470 <p> 4471 4472 4473 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~queryerror'>QueryError</a></span></span> 4474 </p> 4475 </div> 4476 <div> 4477 4478 4479 <div data-ice="description"><p>Thrown when a query is passed invalid options (see message for details)</p> 4480</div> 4481 </div> 4482 </td> 4483 <td> 4484 4485 4486 </td> 4487 </tr> 4488<tr data-ice="target"> 4489 <td> 4490 <span class="access" data-ice="access">public</span> 4491 4492 4493 4494 <span class="override" data-ice="override"></span> 4495 </td> 4496 <td> 4497 <div> 4498 <p> 4499 4500 4501 <span data-ice="name"><span><a href='/v4/class/lib/query-interface.js~queryinterface'>QueryInterface</a></span></span> 4502 </p> 4503 </div> 4504 <div> 4505 4506 4507 <div data-ice="description"><p>The interface that Sequelize uses to talk to all databases</p> 4508</div> 4509 </div> 4510 </td> 4511 <td> 4512 4513 4514 </td> 4515 </tr> 4516<tr data-ice="target"> 4517 <td> 4518 <span class="access" data-ice="access">public</span> 4519 4520 4521 4522 <span class="override" data-ice="override"></span> 4523 </td> 4524 <td> 4525 <div> 4526 <p> 4527 4528 4529 <span data-ice="name"><span><a href='/v4/class/lib/sequelize.js~sequelize'>Sequelize</a></span></span> 4530 </p> 4531 </div> 4532 <div> 4533 4534 4535 <div data-ice="description"><p>This is the main class, the entry point to sequelize.</p> 4536</div> 4537 </div> 4538 </td> 4539 <td> 4540 4541 4542 </td> 4543 </tr> 4544<tr data-ice="target"> 4545 <td> 4546 <span class="access" data-ice="access">public</span> 4547 4548 4549 4550 <span class="override" data-ice="override"></span> 4551 </td> 4552 <td> 4553 <div> 4554 <p> 4555 4556 4557 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~sequelizescopeerror'>SequelizeScopeError</a></span></span> 4558 </p> 4559 </div> 4560 <div> 4561 4562 4563 <div data-ice="description"><p>Scope Error.</p> 4564</div> 4565 </div> 4566 </td> 4567 <td> 4568 4569 4570 </td> 4571 </tr> 4572<tr data-ice="target"> 4573 <td> 4574 <span class="access" data-ice="access">public</span> 4575 4576 4577 4578 <span class="override" data-ice="override"></span> 4579 </td> 4580 <td> 4581 <div> 4582 <p> 4583 4584 4585 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~timeouterror'>TimeoutError</a></span></span> 4586 </p> 4587 </div> 4588 <div> 4589 4590 4591 <div data-ice="description"><p>Thrown when a database query times out because of a deadlock</p> 4592</div> 4593 </div> 4594 </td> 4595 <td> 4596 4597 4598 </td> 4599 </tr> 4600<tr data-ice="target"> 4601 <td> 4602 <span class="access" data-ice="access">public</span> 4603 4604 4605
4606 <span class="override" data-ice="override"></span> 4607 </td> 4608 <td> 4609 <div> 4610 <p> 4611 4612 4613 <span data-ice="name"><span><a href='/v4/class/lib/transaction.js~transaction'>Transaction</a></span></span> 4614 </p> 4615 </div> 4616 <div> 4617 4618 4619 <div data-ice="description"><p>The transaction object is used to identify a running transaction.</p> 4620</div> 4621 </div> 4622 </td> 4623 <td> 4624 4625 4626 </td> 4627 </tr> 4628<tr data-ice="target"> 4629 <td> 4630 <span class="access" data-ice="access">public</span> 4631 4632 4633 4634 <span class="override" data-ice="override"></span> 4635 </td> 4636 <td> 4637 <div> 4638 <p> 4639 4640 4641 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~uniqueconstrainterror'>UniqueConstraintError</a></span></span> 4642 </p> 4643 </div> 4644 <div> 4645 4646 4647 <div data-ice="description"><p>Thrown when a unique constraint is violated in the database</p> 4648</div> 4649 </div> 4650 </td> 4651 <td> 4652 4653 4654 </td> 4655 </tr> 4656<tr data-ice="target"> 4657 <td> 4658 <span class="access" data-ice="access">public</span> 4659 4660 4661 4662 <span class="override" data-ice="override"></span> 4663 </td> 4664 <td> 4665 <div> 4666 <p> 4667 4668 4669 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~unknownconstrainterror'>UnknownConstraintError</a></span></span> 4670 </p> 4671 </div> 4672 <div> 4673 4674 4675 <div data-ice="description"><p>Thrown when constraint name is not found in the database</p> 4676</div> 4677 </div> 4678 </td> 4679 <td> 4680 4681 4682 </td> 4683 </tr> 4684<tr data-ice="target"> 4685 <td> 4686 <span class="access" data-ice="access">public</span> 4687 4688 4689 4690 <span class="override" data-ice="override"></span> 4691 </td> 4692 <td> 4693 <div> 4694 <p> 4695 4696 4697 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~validationerror'>ValidationError</a></span></span><span data-ice="signature">(message: <span>string</span>, errors: <span>Array</span>)</span> 4698 </p> 4699 </div> 4700 <div> 4701 4702 4703 <div data-ice="description"><p>Validation Error.</p> 4704</div> 4705 </div> 4706 </td> 4707 <td> 4708 4709 4710 </td> 4711 </tr> 4712<tr data-ice="target"> 4713 <td> 4714 <span class="access" data-ice="access">public</span> 4715 4716 4717 4718 <span class="override" data-ice="override"></span> 4719 </td> 4720 <td> 4721 <div> 4722 <p> 4723 4724 4725 <span data-ice="name"><span><a href='/v4/class/lib/errors/index.js~validationerroritem'>ValidationErrorItem</a></span></span><span data-ice="signature">(message: <span>String</span>, type: <span>String</span>, path: <span>String</span>, value: <span>String</span>, inst: <span>Object</span>, validatorKey: <span>Object</span>, fnName: <span>String</span>, fnArgs: <span>String</span>)</span> 4726 </p> 4727 </div> 4728 <div> 4729 4730 4731 <div data-ice="description"><p>Validation Error Item 4732Instances of this class are included in the <code>ValidationError.errors</code> property.</p> 4733</div> 4734 </div> 4735 </td> 4736 <td> 4737 4738 4739 </td> 4740 </tr> 4741</tbody> 4742</table> 4743</div> 4744 4745<div data-ice="functionSummary"><h2 id="function">Function Summary</h2><table class="summary" data-ice="summary"> 4746 <thead><tr><td data-ice="title" colspan="3">Static Public Function Summary</td></tr></thead> 4747 <tbody> 4748 4749 <tr data-ice="target"> 4750 <td> 4751 <span class="access" data-ice="access">public</span> 4752 4753 4754 4755 <span class="override" data-ice="override"></span> 4756 </td> 4757 <td> 4758 <div> 4759 <p> 4760 4761 4762 <span data-ice="name"><span><a href='/v4/function/#static-function-isImmutable'>isImmutable</a></span></span><span data-ice="signature">(value: <span>*</span>, validatorArgs: <span>*</span>, field: <span>*</span>, modelInstance: <span>*</span>): <span>*</span></span> 4763 </p> 4764 </div> 4765 <div> 4766 4767 4768 <div data-ice="description"><p>Instance based validators</p> 4769</div> 4770 </div> 4771 </td> 4772 <td> 4773 4774 4775 </td> 4776 </tr> 4777</tbody> 4778</table> 4779</div> 4780<div data-ice="variableSummary"><h2 id="variable">Variable Summary</h2><table class="summary" data-ice="summary"> 4781 <thead><tr><td data-ice="title" colspan="3">Static Public Variable Summary</td></tr></thead> 4782 <tbody> 4783 4784 <tr data-ice="target"> 4785 <td>
4786 <span class="access" data-ice="access">public</span> 4787 4788 4789 4790 <span class="override" data-ice="override"></span> 4791 </td> 4792 <td> 4793 <div> 4794 <p> 4795 4796 4797 <span data-ice="name"><span><a href='/v4/variable/#static-variable-DataTypes'>DataTypes</a></span></span><span data-ice="signature">: <span>*</span></span> 4798 </p> 4799 </div> 4800 <div> 4801 4802 4803 <div data-ice="description"><p>A convenience class holding commonly used data types.</p> 4804</div> 4805 </div> 4806 </td> 4807 <td> 4808 4809 4810 </td> 4811 </tr> 4812<tr data-ice="target"> 4813 <td> 4814 <span class="access" data-ice="access">public</span> 4815 4816 4817 4818 <span class="override" data-ice="override"></span> 4819 </td> 4820 <td> 4821 <div> 4822 <p> 4823 4824 4825 <span data-ice="name"><span><a href='/v4/variable/#static-variable-Deferrable'>Deferrable</a></span></span><span data-ice="signature">: <span>*</span></span> 4826 </p> 4827 </div> 4828 <div> 4829 4830 4831 <div data-ice="description"><p>A collection of properties related to deferrable constraints.</p> 4832</div> 4833 </div> 4834 </td> 4835 <td> 4836 4837 4838 </td> 4839 </tr> 4840<tr data-ice="target"> 4841 <td> 4842 <span class="access" data-ice="access">public</span> 4843 4844 4845 4846 <span class="override" data-ice="override"></span> 4847 </td> 4848 <td> 4849 <div> 4850 <p> 4851 4852 4853 <span data-ice="name"><span><a href='/v4/variable/#static-variable-Op'>Op</a></span></span><span data-ice="signature">: {"eq": <span>*</span>, "ne": <span>*</span>, "gte": <span>*</span>, "gt": <span>*</span>, "lte": <span>*</span>, "lt": <span>*</span>, "not": <span>*</span>, "is": <span>*</span>, "in": <span>*</span>, "notIn": <span>*</span>, "like": <span>*</span>, "notLike": <span>*</span>, "iLike": <span>*</span>, "notILike": <span>*</span>, "regexp": <span>*</span>, "notRegexp": <span>*</span>, "iRegexp": <span>*</span>, "notIRegexp": <span>*</span>, "between": <span>*</span>, "notBetween": <span>*</span>, "overlap": <span>*</span>, "contains": <span>*</span>, "contained": <span>*</span>, "adjacent": <span>*</span>, "strictLeft": <span>*</span>, "strictRight": <span>*</span>, "noExtendRight": <span>*</span>, "noExtendLeft": <span>*</span>, "and": <span>*</span>, "or": <span>*</span>, "any": <span>*</span>, "all": <span>*</span>, "values": <span>*</span>, "col": <span>*</span>, "placeholder": <span>*</span>, "join": <span>*</span>, "raw": <span>*</span>}</span> 4854 </p> 4855 </div> 4856 <div> 4857 4858 4859 <div data-ice="description"><p>Operator symbols to be used when querying data</p> 4860</div> 4861 </div> 4862 </td> 4863 <td> 4864 4865 4866 </td> 4867 </tr> 4868<tr data-ice="target"> 4869 <td> 4870 <span class="access" data-ice="access">public</span> 4871 4872 4873 4874 <span class="override" data-ice="override"></span> 4875 </td> 4876 <td> 4877 <div> 4878 <p> 4879 4880 4881 <span data-ice="name"><span><a href='/v4/variable/#static-variable-QueryTypes'>QueryTypes</a></span></span><span data-ice="signature">: <span>*</span></span> 4882 </p> 4883 </div> 4884 <div> 4885 4886 4887 <div data-ice="description"><p>An enum of query types used by <code>sequelize.query</code></p> 4888</div> 4889 </div> 4890 </td> 4891 <td> 4892 4893 4894 </td> 4895 </tr> 4896<tr data-ice="target"> 4897 <td> 4898 <span class="access" data-ice="access">public</span> 4899 4900 4901 4902 <span class="override" data-ice="override"></span> 4903 </td> 4904 <td> 4905 <div> 4906 <p> 4907 4908 4909 <span data-ice="name"><span><a href='/v4/variable/#static-variable-TableHints'>TableHints</a></span></span><span data-ice="signature">: <span>*</span></span> 4910 </p> 4911 </div> 4912 <div> 4913 4914 4915 <div data-ice="description"><p>An enum of table hints to be used in mssql for querying with table hints</p> 4916</div> 4917 </div> 4918 </td> 4919 <td> 4920 4921 4922 </td> 4923 </tr> 4924</tbody> 4925</table> 4926</div> 4927 4928 4929</div> 4930 <a data-ice='link' href='/v4/identifiers'></a> 4931 </div> 4932 </div> 4933<div class="manual-card-wrap" data-ice="cards"> 4934 <h1 data-ice="label" class="manual-color manual-color-faq" data-section-count="â "><span data-ice="label-inner">Who's using sequelize?</span></h1> 4935 <div class="manual-card"> 4936 <div data-ice="card"><h1>Who's using sequelize?</h1><p><a href="http://www.walmartlabs.com/"><img src="/v4/./manual/asset/walmart-labs-logo.png" alt="Walmart labs logo"></a></p><blockquote> 4937<p>... we are avid users of sequelize (and have been for the past 18 months) (Feb 2017)</p> 4938</blockquote><p></p><hr> 4939 4940<p></p><p><a href="https://snaplytics.io"><img src="/v4/./manual/asset/logo-snaplytics-green.png" alt="Snaplytics logo"></a></p><blockquote> 4941<p>We've been using sequelize since we started in the beginning of 2015. We use it for our graphql servers (in connection with <a href="https://github.com/mickhansen/graphql-sequelize">graphql-sequelize</a>), and for all our background workers.</p> 4942</blockquote><p></p><hr> 4943 4944<p></p><p><a href="https://connectedcars.io/"><img src="/v4/./manual/asset/connected-cars.png" alt="Connected Cars logo"></a></p><p></p><hr> 4945 4946<p></p><p><a href="https://bitovi.com"><img src="/v4/./manual/asset/bitovi-logo.png" alt="Bitovi Logo"></a></p><blockquote> 4947<p>We have used Sequelize in enterprise projects for some of our Fortune 100 and Fortune 500 clients. It is used in deployments that are depended on by hundreds of millions of devices every year.</p> 4948</blockquote><p></p><hr> 4949 4950<p></p><p><a href="https://ermeshotels.com"><img src="/v4/./manual/asset/ermeshotels-logo.png" alt="ErmesHotels Logo"></a></p><blockquote> 4951<p>Using Sequelize in production for two different apps with 30k+ daily users by 2 years. I doubt there is something better at this moment in terms of productivity and features.</p> 4952</blockquote></div> 4953 <a data-ice='link' href='/v4/manual/faq/whos-using'></a> 4954 </div> 4955 </div> 4956<div class="manual-card-wrap" data-ice="cards"> 4957 <h1 data-ice="label" class="manual-color manual-color-faq" data-section-count="â "><span data-ice="label-inner">Imprint</span></h1> 4958 <div class="manual-card"> 4959 <div data-ice="card"><h1>Imprint</h1><ul> 4960<li>Boring legal stuff for the rest of us. 4961As there are people who are suing for fun and glory, you can find the respective information about the author of the page right here. Have fun reading ...</li> 4962</ul><h2>AUTHOR(S)</h2><pre><code><code class="source-code prettyprint">Main author: 4963 4964Sascha Depold 4965Uhlandstr. 160 496610719 Berlin 4967sascha [at] depold [dot] com 4968[plus] 49 152 [slash] 03878582</code> 4969</code></pre><h2>INHALTLICHE VERANTWORTUNG</h2><pre><code><code class="source-code prettyprint">Ich übernehme keine Haftung für ausgehende Links. 4970Daher musst du dich bei Problemen an deren Betreiber wenden!</code> 4971</code></pre></div> 4972 <a data-ice='link' href='/v4/manual/faq/imprint'></a> 4973 </div> 4974 </div> 4975</div> 4976</div> 4977</div> 4978 4979<footer class="footer"> 4980 Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(0.5.2)</span><img src="/v4/./image/esdoc-logo-mini-black.png"></a> 4981</footer>
vendor: 112 bytes, lines 4981-4985
4981 4982 4983 4984 4985<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script>
4985<script src="/v4/script/pretty-print.js"></script>
4985 4986 4987 4988
4989<script src="/v4/script/patch-for-local.js"></script>
4989 4990 4991
4992<script type="module" src="https://static.cloudflareinsights.com/beacon.min.js/v31edd6df95cf4e85bb4c19e7a9bdbcba1788362987495" integrity="sha512-iIg7k2xntmwu6/uSb5tpc/hySgZc4eoL31yB29W6tJFo2akwjPWcEqnCEdJvGexCL0KEQwVYv5BlowfhVz26hg==" data-cf-beacon='{"version":"2024.11.0","token":"b27fb071592e433eb4677c169d09bf4a","r":1,"spa":2}' crossorigin="anonymous"></script>
4992 4993</body></html>
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.