### Define Models and Associations Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/eager-loading.md Setup models and define associations to prepare for eager loading examples. ```javascript const User = sequelize.define('user', { name: DataTypes.STRING }, { timestamps: false }); const Task = sequelize.define('task', { name: DataTypes.STRING }, { timestamps: false }); const Tool = sequelize.define( 'tool', { name: DataTypes.STRING, size: DataTypes.STRING, }, { timestamps: false }, ); User.hasMany(Task); Task.belongsTo(User); User.hasMany(Tool, { as: 'Instruments' }); ``` -------------------------------- ### Start Development Server Source: https://github.com/sequelize/website/blob/main/readme.md Launch the local development server with live reloading. ```bash yarn start ``` -------------------------------- ### Install Dependencies Source: https://github.com/sequelize/website/blob/main/readme.md Install local dependencies and sync the Sequelize repository for documentation generation. ```bash # install local dependencies using yarn yarn # download the sequelize repository (used for including tested code snippets & generating jsdoc) yarn sync ``` -------------------------------- ### Full Runnable Example: Game Championship Model Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/advanced-many-to-many.md A complete Sequelize setup demonstrating the modeling of a game championship with players, teams, games, and their complex relationships. Includes model definitions and initial data seeding. ```javascript const { Sequelize, Op, Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:', { define: { timestamps: false }, // Just for less clutter in this example }); const Player = sequelize.define('Player', { username: DataTypes.STRING }); const Team = sequelize.define('Team', { name: DataTypes.STRING }); const Game = sequelize.define('Game', { name: DataTypes.STRING }); // We apply a Super Many-to-Many relationship between Game and Team const GameTeam = sequelize.define('GameTeam', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false, }, }); Team.belongsToMany(Game, { through: GameTeam }); Game.belongsToMany(Team, { through: GameTeam }); GameTeam.belongsTo(Game); GameTeam.belongsTo(Team); Game.hasMany(GameTeam); Team.hasMany(GameTeam); // We apply a Super Many-to-Many relationship between Player and GameTeam const PlayerGameTeam = sequelize.define('PlayerGameTeam', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false, }, }); Player.belongsToMany(GameTeam, { through: PlayerGameTeam }); GameTeam.belongsToMany(Player, { through: PlayerGameTeam }); PlayerGameTeam.belongsTo(Player); PlayerGameTeam.belongsTo(GameTeam); Player.hasMany(PlayerGameTeam); GameTeam.hasMany(PlayerGameTeam); (async () => { await sequelize.sync(); await Player.bulkCreate([ { username: 's0me0ne' }, { username: 'empty' }, { username: 'greenhead' }, { username: 'not_spock' }, { username: 'bowl_of_petunias' }, ]); await Game.bulkCreate([ { name: 'The Big Clash' }, { name: 'Winter Showdown' }, { name: 'Summer Beatdown' }, ]); await Team.bulkCreate([ { name: 'The Martians' }, { name: 'The Earthlings' }, { name: 'The Plutonians' }, ]); // Let's start defining which teams were in which games. This can be done ``` -------------------------------- ### Install Sequelize Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/getting-started.md Install the core Sequelize package via npm. ```sh npm install --save sequelize ``` -------------------------------- ### Sequelize Migration File Example Source: https://context7.com/sequelize/website/llms.txt Example of a Sequelize migration file defining the 'up' and 'down' methods for creating and dropping a 'Users' table with specified attributes and an index. ```javascript // migrations/20231201-create-user.js module.exports = { up: async (queryInterface, Sequelize) => { await queryInterface.createTable('Users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, firstName: { type: Sequelize.STRING, allowNull: false }, lastName: { type: Sequelize.STRING }, email: { type: Sequelize.STRING, unique: true }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); await queryInterface.addIndex('Users', ['email']); }, down: async (queryInterface, Sequelize) => { await queryInterface.dropTable('Users'); } }; ``` -------------------------------- ### Install Database Drivers Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/getting-started.md Install the specific driver required for your chosen database. ```sh # One of the following: $ npm install --save pg pg-hstore # Postgres $ npm install --save mysql2 $ npm install --save mariadb $ npm install --save sqlite3 $ npm install --save tedious # Microsoft SQL Server $ npm install --save oracledb # Oracle ``` -------------------------------- ### Install Sequelize CLI Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Install the Sequelize CLI as a development dependency in your project. ```text npm install --save-dev sequelize-cli ``` -------------------------------- ### Install Sequelize and Database Drivers Source: https://context7.com/sequelize/website/llms.txt Use npm to install the core Sequelize package and the specific driver required for your database dialect. ```bash # Install Sequelize npm install --save sequelize # Install one of the following database drivers: npm install --save pg pg-hstore # PostgreSQL npm install --save mysql2 # MySQL npm install --save mariadb # MariaDB npm install --save sqlite3 # SQLite npm install --save tedious # Microsoft SQL Server npm install --save oracledb # Oracle ``` -------------------------------- ### Setup One-to-Many Relationships Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/advanced-many-to-many.md Configures two One-to-Many relationships: User to Grant and Profile to Grant. This approach automatically adds userId and profileId columns to the Grant model, similar to the Many-to-Many setup. ```javascript // Setup a One-to-Many relationship between User and Grant User.hasMany(Grant); Grant.belongsTo(User); // Also setup a One-to-Many relationship between Profile and Grant Profile.hasMany(Grant); Grant.belongsTo(Profile); ``` -------------------------------- ### get Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/associations/has-many.js~HasMany.html Get everything currently associated with the source instance, using an optional where clause. ```APIDOC ## get ### Description Get everything currently associated with this, using an optional where clause. ### Parameters - **instances** (Model | Array) - Required - source instances - **options** (object) - Optional - find options - **options.where** (object) - Optional - An optional where clause to limit the associated models - **options.scope** (string | boolean) - Optional - Apply a scope on the related model, or remove its default scope by passing false - **options.schema** (string) - Optional - Apply a schema on the related model ### Response - **Promise>** - Returns a promise that resolves to an array of associated models. ``` -------------------------------- ### Local Development Setup Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/getting-started.md A minimal boilerplate for testing Sequelize locally using an in-memory SQLite database. ```js const { Sequelize, Op, Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); // Code here! It works! ``` -------------------------------- ### Setup Sequelize Model Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-instances.md Initializes the Sequelize environment and defines a User model for subsequent operations. ```javascript const { Sequelize, Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('user', { name: DataTypes.TEXT, favoriteColor: { type: DataTypes.TEXT, defaultValue: 'green', }, age: DataTypes.INTEGER, cash: DataTypes.INTEGER, }); (async () => { await sequelize.sync({ force: true }); // Code here })(); ``` -------------------------------- ### Initialize and use a Sequelize model Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/index.md Demonstrates basic setup including model definition, database synchronization, and record creation using an in-memory SQLite database. ```js const { Sequelize, Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); class User extends Model {} User.init( { username: DataTypes.STRING, birthday: DataTypes.DATE, }, { sequelize, modelName: 'user' }, ); (async () => { await sequelize.sync(); const jane = await User.create({ username: 'janedoe', birthday: new Date(1980, 6, 20), }); console.log(jane.toJSON()); })(); ``` -------------------------------- ### Define Models and Associations Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/scopes.md Setup for Foo, Bar, Baz, and Qux models with One-to-Many associations. ```javascript const Foo = sequelize.define('Foo', { name: Sequelize.STRING }); const Bar = sequelize.define('Bar', { name: Sequelize.STRING }); const Baz = sequelize.define('Baz', { name: Sequelize.STRING }); const Qux = sequelize.define('Qux', { name: Sequelize.STRING }); Foo.hasMany(Bar, { foreignKey: 'fooId' }); Bar.hasMany(Baz, { foreignKey: 'barId' }); Baz.hasMany(Qux, { foreignKey: 'bazId' }); ``` -------------------------------- ### Define dynamic database configuration Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Example of a dynamic configuration file using environment variables and custom dialect options. ```javascript const fs = require('fs'); module.exports = { development: { username: 'database_dev', password: 'database_dev', database: 'database_dev', host: '127.0.0.1', port: 3306, dialect: 'mysql', dialectOptions: { bigNumberStrings: true, }, }, test: { username: process.env.CI_DB_USERNAME, password: process.env.CI_DB_PASSWORD, database: process.env.CI_DB_NAME, host: '127.0.0.1', port: 3306, dialect: 'mysql', dialectOptions: { bigNumberStrings: true, }, }, production: { username: process.env.PROD_DB_USERNAME, password: process.env.PROD_DB_PASSWORD, database: process.env.PROD_DB_NAME, host: process.env.PROD_DB_HOSTNAME, port: process.env.PROD_DB_PORT, dialect: 'mysql', dialectOptions: { bigNumberStrings: true, ssl: { ca: fs.readFileSync(__dirname + '/mysql-ca-main.crt'), }, }, }, }; ``` -------------------------------- ### Enable Babel in .sequelizerc Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Install and register babel-register to support modern syntax in migrations and seeders. ```text npm i --save-dev babel-register ``` ```javascript // .sequelizerc require('babel-register'); const path = require('path'); module.exports = { config: path.resolve('config', 'config.json'), 'models-path': path.resolve('models'), 'seeders-path': path.resolve('seeders'), 'migrations-path': path.resolve('migrations'), }; ``` -------------------------------- ### Setup Sequelize Model with Validations and Constraints Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/validations-and-constraints.md Initializes a Sequelize instance and defines a User model with basic constraints and regex validation. ```js const { Sequelize, Op, Model, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('user', { username: { type: DataTypes.TEXT, allowNull: false, unique: true, }, hashedPassword: { type: DataTypes.STRING(64), validate: { is: /^[0-9a-f]{64}$/i, }, }, }); (async () => { await sequelize.sync({ force: true }); // Code here })(); ``` -------------------------------- ### Example: Foo.hasOne(Bar) Association Methods Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/assocs.md Demonstrates the usage of getBar, setBar, and createBar methods for a hasOne association. Use these to retrieve, update, or create an associated Bar instance for a Foo instance. ```javascript const foo = await Foo.create({ name: 'the-foo' }); const bar1 = await Bar.create({ name: 'some-bar' }); const bar2 = await Bar.create({ name: 'another-bar' }); console.log(await foo.getBar()); // null await foo.setBar(bar1); console.log((await foo.getBar()).name); // 'some-bar' await foo.createBar({ name: 'yet-another-bar' }); const newlyAssociatedBar = await foo.getBar(); console.log(newlyAssociatedBar.name); // 'yet-another-bar' await foo.setBar(null); // Un-associate console.log(await foo.getBar()); // null ``` -------------------------------- ### Polymorphic Eager Loading Output Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/polymorphic-associations.md Example output showing the result of a polymorphic eager load. ```text Found comment #1 with image commentable: { id: 1, title: 'Meow', url: 'https://placekitten.com/408/287', createdAt: 2019-12-26T15:04:53.047Z, updatedAt: 2019-12-26T15:04:53.047Z } ``` -------------------------------- ### Configure Oracle connection Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/dialect-specific-things.md Examples for connecting to an Oracle database using standard parameters, a connection URL, or a custom connect string. ```js const sequelize = new Sequelize('servicename', 'username', 'password', { dialect: 'oracle', host: 'hostname', port: 'port number', //optional }); ``` ```js const sequelize = new Sequelize('oracle://user:pass@hostname:port/servicename'); ``` ```js const sequelize = new Sequelize({ dialect: 'oracle', username: 'user', password: 'password', dialectOptions: { connectString: 'inst1', }, }); ``` -------------------------------- ### Create Table Migration Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Example of defining a table structure with specific data types and constraints. ```javascript module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Person', { name: Sequelize.DataTypes.STRING, isBetaMember: { type: Sequelize.DataTypes.BOOLEAN, defaultValue: false, allowNull: false, }, }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Person'); }, }; ``` -------------------------------- ### Raw SQL Sub-query Example Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/sub-queries.md A raw SQL query demonstrating how to count specific reactions per post. ```sql SELECT *, ( SELECT COUNT(*) FROM reactions AS reaction WHERE reaction.postId = post.id AND reaction.type = "Laugh" ) AS laughReactionsCount FROM posts AS post ``` -------------------------------- ### Configure Sequelize Options Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/sequelize.js~Sequelize.html Provides a comprehensive example of configuring dialect-specific settings, connection pooling, and global model definitions. ```javascript // option examples const sequelize = new Sequelize('database', 'username', 'password', { // the sql dialect of the database // currently supported: 'mysql', 'sqlite', 'postgres', 'mssql' dialect: 'mysql', // custom host; default: localhost host: 'my.server.tld', // for postgres, you can also specify an absolute path to a directory // containing a UNIX socket to connect over // host: '/sockets/psql_sockets'. // custom port; default: dialect default port: 12345, // custom protocol; default: 'tcp' // postgres only, useful for Heroku protocol: null, // disable logging or provide a custom logging function; default: console.log logging: false, // you can also pass any dialect options to the underlying dialect library // - default is empty // - currently supported: 'mysql', 'postgres', 'mssql' dialectOptions: { socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock', supportBigNumbers: true, bigNumberStrings: true }, // the storage engine for sqlite // - default ':memory:' storage: 'path/to/database.sqlite', // disable inserting undefined values as NULL // - default: false omitNull: true, // a flag for using a native library or not. // in the case of 'pg' -- set this to true will allow SSL support // - default: false native: true, // A flag that defines if connection should be over ssl or not // - default: undefined ssl: true, // Specify options, which are used when sequelize.define is called. // The following example: // define: { timestamps: false } // is basically the same as: // Model.init(attributes, { timestamps: false }); // sequelize.define(name, attributes, { timestamps: false }); // so defining the timestamps for each model will be not necessary define: { underscored: false, freezeTableName: false, charset: 'utf8', dialectOptions: { collate: 'utf8_general_ci' }, timestamps: true }, // similar for sync: you can define this to always force sync for models sync: { force: true }, // pool configuration used to pool database connections pool: { max: 5, idle: 30000, acquire: 60000, }, // isolation level of each transaction // defaults to dialect default isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ }) ``` -------------------------------- ### Adding Constraints Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/abstract/query-interface.js~QueryInterface.html Examples of adding different types of constraints to tables using queryInterface.addConstraint. ```APIDOC ## Adding Constraints ### UNIQUE Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['email'], type: 'unique', name: 'custom_unique_constraint_name' }); ``` ### CHECK Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['roles'], type: 'check', where: { roles: ['user', 'admin', 'moderator', 'guest'] } }); ``` ### DEFAULT Constraint (MSSQL only) ```javascript queryInterface.addConstraint('Users', { fields: ['roles'], type: 'default', defaultValue: 'guest' }); ``` ### PRIMARY KEY Constraint ```javascript queryInterface.addConstraint('Users', { fields: ['username'], type: 'primary key', name: 'custom_primary_constraint_name' }); ``` ### FOREIGN KEY Constraint ```javascript queryInterface.addConstraint('Posts', { fields: ['username'], type: 'foreign key', name: 'custom_fkey_constraint_name', references: { table: 'target_table_name', field: 'target_column_name' }, onDelete: 'cascade', onUpdate: 'cascade' }); ``` ### COMPOSITE FOREIGN KEY Constraint ```javascript queryInterface.addConstraint('TableName', { fields: ['source_column_name', 'other_source_column_name'], type: 'foreign key', name: 'custom_fkey_constraint_name', references: { table: 'target_table_name', fields: ['target_column_name', 'other_target_column_name'] }, onDelete: 'cascade', onUpdate: 'cascade' }); ``` ``` -------------------------------- ### npm Script Usage Example Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Execute npm scripts that utilize the --url connection string option by appending the necessary '--' separator before the --url flag. ```text npm run migrate:up -- --url ``` -------------------------------- ### Successful instance creation with hooks Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/hooks.md Example of a successful model creation that passes hook validation. ```javascript const user = await User.create({ username: 'Boss', accessLevel: 20 }); console.log(user); // user object with username 'Boss' and accessLevel of 20 ``` -------------------------------- ### Polymorphic Eager Loading Placeholder Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/polymorphic-associations.md An example of the desired syntax for polymorphic eager loading. ```js const comment = await Comment.findOne({ include: [ /* What to put here? */ ], }); console.log(comment.commentable); // This is our goal ``` -------------------------------- ### PostgreSQL SQL Output for One-To-Many Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/assocs.md Example SQL generated by Sequelize for a one-to-many relationship. ```sql CREATE TABLE IF NOT EXISTS "Teams" ( /* ... */ ); CREATE TABLE IF NOT EXISTS "Players" ( /* ... */ "TeamId" INTEGER REFERENCES "Teams" ("id") ON DELETE SET NULL ON UPDATE CASCADE, /* ... */ ); ``` -------------------------------- ### Define User and Profile models Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/advanced-many-to-many.md Initial setup for User and Profile models to be used in a Many-to-Many relationship. ```javascript const User = sequelize.define( 'user', { username: DataTypes.STRING, points: DataTypes.INTEGER, }, { timestamps: false }, ); const Profile = sequelize.define( 'profile', { name: DataTypes.STRING, }, { timestamps: false }, ); ``` -------------------------------- ### Describe Table Structure Output Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/sqlite/query-interface.js~SQLiteQueryInterface.html Example of the object structure returned by the describeTable method. ```javascript { name: { type: 'VARCHAR(255)', // this will be 'CHARACTER VARYING' for pg! allowNull: true, defaultValue: null }, isBetaMember: { type: 'TINYINT(1)', // this will be 'BOOLEAN' for pg! allowNull: false, defaultValue: false } } ``` -------------------------------- ### Build and Save Instance Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-instances.md Demonstrates creating an instance in memory using build and persisting it to the database with save. ```javascript const jane = User.build({ name: 'Jane' }); console.log(jane instanceof User); // true console.log(jane.name); // "Jane" ``` ```javascript await jane.save(); console.log('Jane was saved to the database!'); ``` -------------------------------- ### Populate Database with Sample Data Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/sub-queries.md Helper function to create posts and associated reactions for testing sub-queries. ```javascript async function makePostWithReactions(content, reactionTypes) { const post = await Post.create({ content }); await Reaction.bulkCreate(reactionTypes.map(type => ({ type, postId: post.id }))); return post; } await makePostWithReactions('Hello World', [ 'Like', 'Angry', 'Laugh', 'Like', 'Like', 'Angry', 'Sad', 'Like', ]); await makePostWithReactions('My Second Post', ['Laugh', 'Laugh', 'Like', 'Laugh']); ``` -------------------------------- ### Initialize Sequelize Project Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Bootstrap a new Sequelize project structure including config, models, migrations, and seeders folders. ```text npx sequelize-cli init ``` -------------------------------- ### Initialize Sequelize Instance Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/getting-started.md Create a Sequelize instance using a connection URI or by passing configuration parameters. ```js const { Sequelize } = require('sequelize'); // Option 1: Passing a connection URI const sequelize = new Sequelize('sqlite::memory:') // Example for sqlite const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Example for postgres // Option 2: Passing parameters separately (sqlite) const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'path/to/database.sqlite' }); // Option 3: Passing parameters separately (other dialects) const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: /* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */ }); ``` -------------------------------- ### Create Instance Shortcut Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-instances.md Uses the create method to combine building and saving into a single asynchronous operation. ```javascript const jane = await User.create({ name: 'Jane' }); // Jane exists in the database now! console.log(jane instanceof User); // true console.log(jane.name); // "Jane" ``` -------------------------------- ### Validation Result Example Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/validations-and-constraints.md An example of the validation result object returned when a model fails validation, showing both field-specific and model-wide errors. ```json { 'latitude': ['Invalid number: latitude'], 'bothCoordsOrNone': ['Either both latitude and longitude, or neither!'] } ``` -------------------------------- ### Many-to-Many Eager Loading Output Example Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/eager-loading.md Example JSON output when eager loading a Many-to-Many relationship, including the junction table data. ```json { "id": 1, "name": "foo", "Bars": [ { "id": 1, "name": "bar", "Foo_Bar": { "FooId": 1, "BarId": 1 } } ] } ``` -------------------------------- ### transaction Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/sequelize.js~Sequelize.html Starts a transaction. ```APIDOC ## transaction ### Description Start a transaction. ### Method ASYNC ### Endpoint `transaction(options, autoCallback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "options": "object", "autoCallback": "Function" } ``` ### Response #### Success Response (200) Type: Promise #### Response Example ```json { "example": "Promise" } ``` ``` -------------------------------- ### get Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/model.js~Model.html Retrieves the values of the instance's attributes. ```APIDOC ## get ### Description If no key is given, returns all values of the instance, also invoking virtual getters. ### Method [method name not specified, likely instance method] ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **object | any** - The value(s) of the requested attribute(s). #### Response Example N/A ``` -------------------------------- ### GET /queryInterface/describeTable Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/abstract/query-interface.js~QueryInterface.html Retrieves the structure of a given table. ```APIDOC ## GET /queryInterface/describeTable ### Description Describe a table structure. This method returns an array of hashes containing information about all attributes in the table. ### Method GET ### Endpoint /queryInterface/describeTable ### Parameters #### Path Parameters None #### Query Parameters - **tableName** (string) - Required - table name - **options** (object) - Optional - Query options ### Request Example ```json { "tableName": "users", "options": {} } ``` ### Response #### Success Response (200) - **Promise** - A promise that resolves with an object describing the table structure. #### Response Example ```json { "name": { "type": "VARCHAR(255)", "allowNull": true, "defaultValue": null }, "isBetaMember": { "type": "TINYINT(1)", "allowNull": false, "defaultValue": false } } ``` ``` -------------------------------- ### random Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/sequelize.js~Sequelize.html Gets the function for random based on the dialect. ```APIDOC ## random ### Description Get the fn for random based on the dialect. ### Method PUBLIC ### Endpoint `random()` ### Parameters None ### Request Example None ### Response #### Success Response (200) Type: fn #### Response Example ```json { "example": "fn" } ``` ``` -------------------------------- ### getDataValue Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/model.js~Model.html Gets the raw value of a data value for a given key. ```APIDOC ## getDataValue ### Description Get the value of the underlying data value. ### Method [method name not specified, likely instance method] ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **any** - The value of the data value. #### Response Example N/A ``` -------------------------------- ### Connect to a Database Source: https://context7.com/sequelize/website/llms.txt Initialize a Sequelize instance using a connection URI or configuration parameters, and verify the connection with authenticate(). ```javascript const { Sequelize } = require('sequelize'); // Option 1: Connection URI const sequelize = new Sequelize('postgres://user:pass@localhost:5432/dbname'); // Option 2: SQLite with file path const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'path/to/database.sqlite' }); // Option 3: Separate parameters for other dialects const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql', logging: console.log, // or false to disable pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }); // Test the connection async function testConnection() { try { await sequelize.authenticate(); console.log('Connection established successfully.'); } catch (error) { console.error('Unable to connect:', error); } } // Close connection when done await sequelize.close(); ``` -------------------------------- ### get Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/associations/has-one.js~HasOne.html Retrieves the associated instance for a given source instance or array of instances. ```APIDOC ## get ### Description Get the associated instance. ### Parameters - **instances** (Model | Array) - Required - The source instance or array of instances - **options** (object) - Optional - Options for the retrieval ### Response - **Promise** - The associated instance ``` -------------------------------- ### Sequelize Constructor Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/sequelize.js~Sequelize.html Instantiate Sequelize with the name of the database, username, and password. ```APIDOC ## Sequelize Constructor ### Description Instantiate sequelize with name of database, username and password. ### Method constructor ### Parameters #### Path Parameters - **database** (string) - Required - The name of the database. - **username** (string) - Required - The username for database authentication. - **password** (string) - Required - The password for database authentication. - **options** (object) - Optional - Additional configuration options for Sequelize. ``` -------------------------------- ### GET /model/getDataValue Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/model.js~Model.html Retrieves the raw underlying data value from the instance data store. ```APIDOC ## GET /model/getDataValue ### Description Fetches the value directly from the underlying data store of the instance. ### Parameters #### Query Parameters - **key** (string) - Required - The key to look up in the instance data store. ### Response #### Success Response (200) - **value** (any) - The raw data value. ``` -------------------------------- ### Get Foreign Keys for Tables Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/db2/query-interface.js~Db2QueryInterface.html Returns all foreign key constraints for the requested tables. ```APIDOC ## async getForeignKeysForTables(tableNames, options) ### Description Returns all foreign key constraints of requested tables. ### Method ASYNC ### Endpoint Not applicable (method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None specified #### Response Example None ``` -------------------------------- ### Define scopes for merging Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/scopes.md Example model scope definitions to demonstrate merging behavior. ```js YourModel.addScope('scope1', { where: { firstName: 'bob', age: { [Op.gt]: 20, }, }, limit: 2, }); YourModel.addScope('scope2', { where: { age: { [Op.lt]: 30, }, }, limit: 10, }); ``` -------------------------------- ### Sequelize Configuration Options Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/sequelize.js~Sequelize.html Configuration settings for Sequelize instance initialization. ```APIDOC ## Sequelize Configuration Options ### Description Configuration options for customizing Sequelize behavior, including transaction management, query retry logic, and global hooks. ### Parameters #### Request Body - **options.isolationLevel** (string) - Optional - Set the default transaction isolation level. - **options.retry** (object) - Optional - Set of flags that control when a query is automatically retried. - **options.retry.match** (Array) - Optional - Only retry a query if the error matches one of these strings. - **options.retry.max** (number) - Optional - How many times a failing query is automatically retried. - **options.typeValidation** (boolean) - Optional - Run built-in type validators on insert and update. - **options.operatorsAliases** (object) - Optional - String based operator alias. - **options.hooks** (object) - Optional - An object of global hook functions. - **options.minifyAliases** (boolean) - Optional - A flag that defines if aliases should be minified. - **options.logQueryParameters** (boolean) - Optional - A flag that defines if show bind parameters in log. ``` -------------------------------- ### Sequelize Constructor Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/sequelize.js~Sequelize.html Initializes a new Sequelize instance with database credentials and configuration options. ```APIDOC ## Constructor: new Sequelize() ### Description Initializes a new Sequelize instance. Can be configured via individual parameters or an options object. ### Parameters - **database** (string) - Optional - Database name - **username** (string) - Optional - Database username - **password** (string) - Optional - Database password - **options** (object) - Optional - Configuration object including dialect, host, port, pool, and dialect-specific settings. ``` -------------------------------- ### Create a new user record Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-querying-basics.md Use `Model.create()` to build and save a new instance in a single step. This method is a shorthand for `Model.build()` followed by `instance.save()`. ```javascript // Create a new user const jane = await User.create({ firstName: 'Jane', lastName: 'Doe' }); console.log("Jane's auto-generated ID:", jane.id); ``` -------------------------------- ### GET /api/tableExists Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/abstract/query-interface.js~QueryInterface.html Checks if a table exists in the database. It returns a boolean indicating the presence of the table. ```APIDOC ## GET /api/tableExists ### Description Returns a promise that will resolve to true if the table exists in the database, false otherwise. ### Method GET ### Endpoint /api/tableExists ### Parameters #### Query Parameters - **tableName** (TableName) - Required - The name of the table. - **options** (QueryOptions) - Required - Query options. ### Response #### Success Response (200) - **exists** (boolean) - True if the table exists, false otherwise. #### Response Example { "exists": true } ``` -------------------------------- ### Get Associated Instances Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/associations/belongs-to-many.js~BelongsToMany.html Retrieves all instances currently associated with a given instance, with optional filtering. ```APIDOC ## GET /api/associations/get ### Description Gets all instances currently associated with this, using an optional where clause. ### Method GET ### Endpoint /api/associations/get ### Parameters #### Path Parameters None #### Query Parameters - **instance** (Model) - Required - The instance to retrieve associations for. - **options** (object) - Optional - Find options. - **options.where** (object) - Optional - An optional where clause to limit the associated models. - **options.scope** (string | boolean) - Optional - Apply a scope on the related model, or remove its default scope by passing false. - **options.schema** (string) - Optional - Apply a schema on the related model. - **options.through.where** (object) - Optional - An optional where clause applied to the through model (join table). - **options.through.paranoid** (boolean) - Optional - Default: true. If true, only non-deleted records will be returned from the join table. If false, both deleted and non-deleted records will be returned. Only applies if the through model is paranoid. ### Request Example ```json { "instance": { /* Model instance data */ }, "options": { "where": { "status": "active" }, "scope": "activeUsers", "schema": "public", "through": { "where": { "role": "admin" }, "paranoid": false } } } ``` ### Response #### Success Response (200) - **Promise>** - A promise that resolves with an array of associated model instances. #### Response Example ```json { "associatedModels": [ { /* Model instance data */ }, { /* Model instance data */ } ] } ``` #### See: - [Model](class/src/model.js~Model.html) for a full explanation of options ``` -------------------------------- ### Generate Model and Migration Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Create a new model and its corresponding migration file using the CLI. ```text npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string ``` -------------------------------- ### Set dynamic configuration file Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Point the CLI to a JavaScript file instead of a JSON file to enable dynamic configuration logic. ```javascript const path = require('path'); module.exports = { config: path.resolve('config', 'config.js'), }; ``` -------------------------------- ### Polymorphic Association SQL Examples Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/advanced-association-concepts/polymorphic-associations.md SQL queries generated by Sequelize when interacting with polymorphic associations. ```sql SELECT "id", "title", "commentableType", "commentableId", "createdAt", "updatedAt" FROM "comments" AS "comment" WHERE "comment"."commentableType" = 'image' AND "comment"."commentableId" = 1; ``` ```sql INSERT INTO "comments" ( "id", "title", "commentableType", "commentableId", "createdAt", "updatedAt" ) VALUES ( DEFAULT, 'Awesome!', 'image', 1, '2018-04-17 05:36:40.454 +00:00', '2018-04-17 05:36:40.454 +00:00' ) RETURNING *; ``` ```sql UPDATE "comments" SET "commentableId"=1, "commentableType"='image', "updatedAt"='2018-04-17 05:38:43.948 +00:00' WHERE "id" IN (1) ``` -------------------------------- ### Deploy Website Source: https://github.com/sequelize/website/blob/main/readme.md Deploy the website to GitHub pages using either SSH or standard authentication. ```bash USE_SSH=true yarn deploy ``` ```bash GIT_USER= yarn deploy ``` -------------------------------- ### Define Model with Integer Column Source: https://github.com/sequelize/website/blob/main/static/api/v6/variable/index.html Example of defining a Sequelize model with a column using DataTypes.INTEGER. ```javascript sequelize.define('model', { column: DataTypes.INTEGER }) ``` -------------------------------- ### GET /api/showAllSchemas Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/abstract/query-interface.js~QueryInterface.html Retrieves a list of all available schemas in the database. This method accepts optional query options. ```APIDOC ## GET /api/showAllSchemas ### Description Shows all schemas in the database. ### Method GET ### Endpoint /api/showAllSchemas ### Parameters #### Query Parameters - **options** (object) - Optional - Query options. ### Response #### Success Response (200) - **schemas** (array) - An array of schema names. #### Response Example { "schemas": ["schema1", "schema2"] } ``` -------------------------------- ### Use Connection String for Migration Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Pass a database connection string directly to the CLI using the --url option for migrations. Ensure proper formatting for the URL. ```text npx sequelize-cli db:migrate --url 'mysql://root:password@mysql_host.com/database_name' ``` -------------------------------- ### Obtain Sequelize Query Interface Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/query-interface.md Get the singleton instance of the QueryInterface from your Sequelize instance to interact with the database. ```javascript const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize(/* ... */); const queryInterface = sequelize.getQueryInterface(); ``` -------------------------------- ### Perform basic equality queries Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-querying-basics.md Demonstrates implicit equality comparison versus explicit Op.eq usage. ```javascript Post.findAll({ where: { authorId: 2, }, }); // SELECT * FROM post WHERE authorId = 2; ``` ```javascript const { Op } = require('sequelize'); Post.findAll({ where: { authorId: { [Op.eq]: 2, }, }, }); // SELECT * FROM post WHERE authorId = 2; ``` -------------------------------- ### static bulkCreate() Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/model.js~Model.html Create and insert multiple instances in bulk into the database. ```APIDOC ## static bulkCreate() ### Description Create and insert multiple instances in bulk. Note that returned instances may not fully represent DB state due to limitations in MySQL/SQLite regarding auto-generated IDs. ### Parameters #### Arguments - **records** (Array) - Required - The records to create. - **options** (object) - Optional - Configuration options for the bulk creation. ### Response - **Returns** (Promise>) - A promise that resolves to an array of instances. If validation fails, the promise is rejected with an AggregateError. ``` -------------------------------- ### Reload Instance from Database Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-instances.md Reload an instance from the database to get the latest data. This generates a SELECT query. ```javascript const jane = await User.create({ name: 'Jane' }); console.log(jane.name); // "Jane" jane.name = 'Ada'; // the name is still "Jane" in the database await jane.reload(); console.log(jane.name); // "Jane" ``` -------------------------------- ### Create associated models using standard methods Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/assocs.md Demonstrates creating an associated record by manually setting the foreign key column. ```js // Example: creating an associated model using the standard methods Bar.create({ name: 'My Bar', fooId: 5, }); // This creates a Bar belonging to the Foo of ID 5 (since fooId is // a regular column, after all). Nothing very clever going on here. ``` -------------------------------- ### Get Foreign Key References Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/mssql/query-interface.js~MSSqlQueryInterface.html API endpoint to retrieve foreign key references for a specific table. ```APIDOC ## GET /query-interface/getForeignKeyReferencesForTable ### Description Get foreign key references details for the table. ### Method GET ### Endpoint /query-interface/getForeignKeyReferencesForTable ### Parameters #### Query Parameters - **tableName** (string) - Required - The name of the table. - **options** (object) - Optional - Query options. ``` -------------------------------- ### Get Foreign Key References for Table Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/dialects/db2/query-interface.js~Db2QueryInterface.html Retrieves foreign key references details for a given table. ```APIDOC ## async getForeignKeyReferencesForTable(tableName, options) ### Description Get foreign key references details for the table. ### Method ASYNC ### Endpoint Not applicable (method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None specified #### Response Example None ``` -------------------------------- ### Define Models for belongsToMany Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/assocs.md Initial model definitions for Foo and Bar entities used in relationship examples. ```js const Foo = sequelize.define( 'foo', { name: { type: DataTypes.TEXT, unique: true }, }, { timestamps: false }, ); const Bar = sequelize.define( 'bar', { title: { type: DataTypes.TEXT, unique: true }, }, { timestamps: false }, ); ``` -------------------------------- ### Build Static Content Source: https://github.com/sequelize/website/blob/main/readme.md Generate static files for production in the build directory. ```bash yarn build ``` -------------------------------- ### Run Migrations Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/migrations.md Execute pending migrations to update the database schema. ```text npx sequelize-cli db:migrate ``` -------------------------------- ### Create Geometry Records Source: https://github.com/sequelize/website/blob/main/static/api/v6/class/src/data-types.js~GEOMETRY.html Examples of creating records with various geometry types using GeoJSON format. ```javascript const point = { type: 'Point', coordinates: [-76.984722, 39.807222]}; // GeoJson format: [lng, lat] User.create({username: 'username', geometry: point }); ``` ```javascript const line = { type: 'LineString', 'coordinates': [ [100.0, 0.0], [101.0, 1.0] ] }; User.create({username: 'username', geometry: line }); ``` ```javascript const polygon = { type: 'Polygon', coordinates: [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ]}; User.create({username: 'username', geometry: polygon }); ``` ```javascript const point = { type: 'Point', coordinates: [-76.984722, 39.807222], // GeoJson format: [lng, lat] crs: { type: 'name', properties: { name: 'EPSG:4326'} } }; User.create({username: 'username', geometry: point }) ``` -------------------------------- ### Synchronize User Model Table (Force Create) Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/model-basics.md Use `User.sync({ force: true })` to create the table for the User model, dropping it first if it already exists. This is useful for development and testing. ```javascript await User.sync({ force: true }); console.log('The table for the User model was just (re)created!'); ``` -------------------------------- ### Set Transaction Isolation Level Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/transactions.md Specify an isolation level when starting a transaction or globally in the Sequelize constructor. ```js const { Transaction } = require('sequelize'); await sequelize.transaction( { isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE, }, async t => { // Your code }, ); ``` ```js const { Sequelize, Transaction } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:', { isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE, }); ``` -------------------------------- ### Default Association Setup Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/core-concepts/assocs.md Demonstrates the default behavior where Sequelize automatically generates the foreign key name. ```js Ship.belongsTo(Captain); // This creates the `captainId` foreign key in Ship. // Eager Loading is done by passing the model to `include`: console.log((await Ship.findAll({ include: Captain })).toJSON()); // Or by providing the associated model name: console.log((await Ship.findAll({ include: 'captain' })).toJSON()); // Also, instances obtain a `getCaptain()` method for Lazy Loading: const ship = Ship.findOne(); console.log((await ship.getCaptain()).toJSON()); ``` -------------------------------- ### Create a Table with Query Interface Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/query-interface.md Use the query interface to define and create a new table with specified columns and their attributes. ```javascript queryInterface.createTable('Person', { name: DataTypes.STRING, isBetaMember: { type: DataTypes.BOOLEAN, defaultValue: false, allowNull: false, }, }); ``` -------------------------------- ### Configure Sequelize for Read Replication Source: https://github.com/sequelize/website/blob/main/versioned_docs/version-6.x.x/other-topics/read-replication.md Instantiate Sequelize with replication options, specifying read replicas and a write server. Pool options can be overridden for read/write pools. Database name and port are propagated to replicas if not specified per instance. ```javascript const sequelize = new Sequelize('database', null, null, { dialect: 'mysql', port: 3306, replication: { read: [ { host: '8.8.8.8', username: 'read-1-username', password: process.env.READ_DB_1_PW, }, { host: '9.9.9.9', username: 'read-2-username', password: process.env.READ_DB_2_PW, }, ], write: { host: '1.1.1.1', username: 'write-username', password: process.env.WRITE_DB_PW, }, }, pool: { // If you want to override the options used for the read/write pool you can do so here max: 20, idle: 30000, }, }); ```