Установка
SKILL.md
Sequelize Skill
Sequelize node.js orm для sql баз данных. Используйте для моделей базы данных, миграций, ассоциаций, запросов, транзакций, валидаций, хуков и работы с postgresql, mysql, mariadb, sqlite, sql server., создано на основе официальной документации.
Когда использовать этот навык
Этот навык следует активировать, когда:
- Работа с sequelize
- Вопросы о функциях или API sequelize
- Реализация решений на sequelize
- Отладка кода sequelize
- Изучение лучших практик sequelize
Быстрый справочник
Общие шаблоны
Шаблон 1: Пул соединений. Если вы подключаетесь к базе данных из одного процесса, вам следует создать только один экземпляр Sequelize. Sequelize настроит пул соединений при инициализации. Этот пул соединений можно настроить через параметр options конструктора (используя options.pool), как показано в следующем примере: const sequelize = new Sequelize(/_ ... _/, { // ... pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }}); Узнайте больше в справочнике API для конструктора Sequelize. Если вы подключаетесь к базе данных из нескольких процессов, вам придется создать один экземпляр на процесс, но каждый экземпляр должен иметь максимальный размер пула соединений таким образом, чтобы соблюдался общий максимальный размер. Например, если вы хотите максимальный размер пула соединений 90 и у вас три процесса, экземпляр Sequelize каждого процесса должен иметь максимальный размер пула соединений 30.
options
Шаблон 2: Стратегии именования. Опция underscored. Sequelize предоставляет опцию underscored для модели. Когда она равна true, эта опция установит опцию field для всех атрибутов в snakecase version of its name. This also applies to foreign keys automatically generated by associations and other automatically generated fields. Example: const User = sequelize.define( 'user', { username: Sequelize.STRING }, { underscored: true, },);const Task = sequelize.define( 'task', { title: Sequelize.STRING }, { underscored: true, },);User.hasMany(Task);Task.belongsTo(User); Above we have the models User and Task, both using the underscored option. We also have a One-to-Many relationship between them. Also, recall that since timestamps is true by default, we should expect the createdAt and updatedAt fields to be automatically created as well. Without the underscored option, Sequelize would automatically define: A createdAt attribute for each model, pointing to a column named createdAt in each table An updatedAt attribute for each model, pointing to a column named updatedAt in each table A userId attribute in the Task model, pointing to a column named userId in the task table With the underscored option enabled, Sequelize will instead define: A createdAt attribute for each model, pointing to a column named created_at in each table An updatedAt attribute for each model, pointing to a column named updated_at in each table A userId attribute in the Task model, pointing to a column named user_id in the task table Note that in both cases the fields are still camelCase in the JavaScript side; this option only changes how these fields are mapped to the database itself. The field option of every attribute is set to their snake_case version, but the attribute itself remains camelCase. This way, calling sync() on the above code will generate the following: CREATE TABLE IF NOT EXISTS "users" ( "id" SERIAL, "username" VARCHAR(255), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL, "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));CREATE TABLE IF NOT EXISTS "tasks" ( "id" SERIAL, "title" VARCHAR(255), "created_at" TIMESTAMP WITH TIME ZONE NOT NULL, "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL, "user_id" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id")); Singular vs. Plural At a first glance, it can be confusing whether the singular form or plural form of a name shall be used around in Sequelize. This section aims at clarifying that a bit. Recall that Sequelize uses a library called inflection under the hood, so that irregular plurals (such as person -> people) are computed correctly. However, if you're working in another language, you may want to define the singular and plural forms of names directly; sequelize allows you to do this with some options. When defining models Models should be defined with the singular form of a word. Example: sequelize.define('foo', { name: DataTypes.STRING }); Above, the model name is foo (singular), and the respective table name is foos, since Sequelize automatically gets the plural for the table name. When defining a reference key in a model sequelize.define('foo', { name: DataTypes.STRING, barId: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'bars', key: 'id', }, onDelete: 'CASCADE', },}); In the above example we are manually defining a key that references another model. It's not usual to do this, but if you have to, you should use the table name there. This is because the reference is created upon the referenced table name. In the example above, the plural form was used (bars), assuming that the bar model was created with the default settings (making its underlying table automatically pluralized). When retrieving data from eager loading When you perform an include in a query, the included data will be added to an extra field in the returned objects, according to the following rules: When including something from a single association (hasOne or belongsTo) - the field name will be the singular version of the model name; When including something from a multiple association (hasMany or belongsToMany) - the field name will be the plural form of the model. In short, the name of the field will take the most logical form in each situation. Examples: // Assuming Foo.hasMany(Bar)const foo = Foo.findOne({ include: Bar });// foo.bars will be an array// foo.bar will not exist since it doens't make sense// Assuming Foo.hasOne(Bar)const foo = Foo.findOne({ include: Bar });// foo.bar will be an object (possibly null if there is no associated model)// foo.bars will not exist since it doens't make sense// And so on. Overriding singulars and plurals when defining aliases When defining an alias for an association, instead of using simply { as: 'myAlias' }, you can pass an object to specify the singular and plural forms: Project.belongsToMany(User, { as: { singular: 'líder', plural: 'líderes', },}); If you know that a model will always use the same alias in associations, you can provide the singular and plural forms directly to the model itself: const User = sequelize.define( 'user', { / ... _/ }, { name: { singular: 'líder', plural: 'líderes', }, },);Project.belongsToMany(User); Миксины, добавленные к экземплярам user, будут использовать правильные формы. Например, вместо project.addUser() Sequelize предоставит project.getLíder(). Также вместо project.setUsers() Sequelize предоставит project.setLíderes(). Примечание: напомним, что использование as для изменения имени ассоциации также изменит имя внешнего ключа. Поэтому в этом случае рекомендуется также явно указать задействованные внешние ключи. // Пример возможной ошибкиInvoice.belongsTo(Subscription, { as: 'TheSubscription' });Subscription.hasMany(Invoice); Первый вызов выше создаст внешний ключ с именем theSubscriptionId в Invoice. Однако второй вызов также создаст внешний ключ в Invoice (поскольку, как мы знаем, вызовы hasMany размещают внешние ключи в целевой модели) — однако он будет называться subscriptionId. Таким образом, у вас будут оба столбца: subscriptionId и theSubscriptionId. Лучший подход — выбрать имя для внешнего ключа и явно указать его в обоих вызовах. Например, если был выбран subscription_id: // Исправленный примерInvoice.belongsTo(Subscription, { as: 'TheSubscription', foreignKey: 'subscription_id',});Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' });
underscored
Шаблон 3: Модели должны определяться в единственном числе слова. Пример:
sequelize.define('foo', { name: DataTypes.STRING });
Шаблон 4: По умолчанию null является допустимым значением для каждого столбца модели. Это можно отключить, установив опцию allowNull: false для столбца, как это было сделано в поле username из нашего примера кода:
null
Шаблон 5: Query InterfaceЭкземпляр Sequelize использует нечто под названием Query Interface для взаимодействия с базой данных независимо от диалекта. Большинство методов, которые вы изучили в этом руководстве, реализованы с помощью нескольких методов из query interface. Таким образом, методы из query interface являются методами более низкого уровня; их следует использовать только в том случае, если вы не нашли другого способа сделать это с помощью высокоуровневых API из Sequelize. Они, конечно, всё ещё более высокоуровневые, чем выполнение сырых запросов напрямую (то есть написание SQL вручную). В этом руководстве показано несколько примеров, но для полного списка того, что он может делать, и для подробного использования каждого метода смотрите QueryInterface API. Получение query interface С этого момента мы будем называть queryInterface синглтон-экземпляром класса QueryInterface, который доступен в вашем экземпляре Sequelize: const { Sequelize, DataTypes } = require('sequelize');const sequelize = new Sequelize(/_ ... /);const queryInterface = sequelize.getQueryInterface(); Создание таблицы queryInterface.createTable('Person', { name: DataTypes.STRING, isBetaMember: { type: DataTypes.BOOLEAN, defaultValue: false, allowNull: false, },}); Сгенерированный SQL (с использованием SQLite): CREATE TABLE IF NOT EXISTS Person ( name VARCHAR(255), isBetaMember TINYINT(1) NOT NULL DEFAULT 0); Примечание: рассмотрите возможность определения Model и вызова YourModel.sync() вместо этого, что является более высокоуровневым подходом. Добавление столбца в таблицу queryInterface.addColumn('Person', 'petName', { type: DataTypes.STRING }); Сгенерированный SQL (с использованием SQLite): ALTER TABLE Person ADD petName VARCHAR(255); Изменение типа данных столбца queryInterface.changeColumn('Person', 'foo', { type: DataTypes.FLOAT, defaultValue: 3.14, allowNull: false,}); Сгенерированный SQL (с использованием MySQL): ALTER TABLE Person CHANGE foo foo FLOAT NOT NULL DEFAULT 3.14; Удаление столбца queryInterface.removeColumn('Person', 'petName', { / параметры запроса _/}); Сгенерированный SQL (с использованием PostgreSQL): ALTER TABLE "public"."Person" DROP COLUMN "petName"; Изменение и удаление столбцов в SQLite SQLite не поддерживает прямое изменение и удаление столбцов. Однако Sequelize попытается обойти это путем пересоздания всей таблицы с помощью резервной таблицы, вдохновленный этими инструкциями. Например: // Предположим, у нас есть таблица в SQLite, созданная следующим образом:queryInterface.createTable('Person', { name: DataTypes.STRING, isBetaMember: { type: DataTypes.BOOLEAN, defaultValue: false, allowNull: false, }, petName: DataTypes.STRING, foo: DataTypes.INTEGER,});// И мы изменяем столбец:queryInterface.changeColumn('Person', 'foo', { type: DataTypes.FLOAT, defaultValue: 3.14, allowNull: false,}); Для SQLite генерируются следующие вызовы SQL: PRAGMA TABLE_INFO(Person);CREATE TABLE IF NOT EXISTS Person_backup ( name VARCHAR(255), isBetaMember TINYINT(1) NOT NULL DEFAULT 0, foo FLOAT NOT NULL DEFAULT '3.14', petName VARCHAR(255));INSERT INTO Person_backup SELECT name, isBetaMember, foo, petName FROM Person;DROP TABLE Person;CREATE TABLE IF NOT EXISTS Person ( name VARCHAR(255), isBetaMember TINYINT(1) NOT NULL DEFAULT 0, foo FLOAT NOT NULL DEFAULT '3.14', petName VARCHAR(255));INSERT INTO Person SELECT name, isBetaMember, foo, petName FROM Person_backup;DROP TABLE Person_backup; Другое Как упоминалось в начале этого руководства, в Sequelize доступно гораздо больше возможностей Query Interface! Ознакомьтесь с API QueryInterface, чтобы получить полный список того, что можно сделать.
queryInterface
Шаблон 6: Advanced M:N AssociationsMake sure you have read the associations guide before reading this guide. Let's start with an example of a Many-to-Many relationship between User and Profile. const User = sequelize.define( 'user', { username: DataTypes.STRING, points: DataTypes.INTEGER, }, { timestamps: false },);const Profile = sequelize.define( 'profile', { name: DataTypes.STRING, }, { timestamps: false },); The simplest way to define the Many-to-Many relationship is: User.belongsToMany(Profile, { through: 'User_Profiles' });Profile.belongsToMany(User, { through: 'User_Profiles' }); By passing a string to through above, we are asking Sequelize to automatically generate a model named User_Profiles as the through table (also known as junction table), with only two columns: userId and profileId. A composite unique key will be established on these two columns. We can also define ourselves a model to be used as the through table. const User_Profile = sequelize.define('User_Profile', {}, { timestamps: false });User.belongsToMany(Profile, { through: User_Profile });Profile.belongsToMany(User, { through: User_Profile }); The above has the exact same effect. Note that we didn't define any attributes on the User_Profile model. The fact that we passed it into a belongsToMany call tells sequelize to create the two attributes userId and profileId automatically, just like other associations also cause Sequelize to automatically add a column to one of the involved models. However, defining the model by ourselves has several advantages. We can, for example, define more columns on our through table: const User_Profile = sequelize.define( 'User_Profile', { selfGranted: DataTypes.BOOLEAN, }, { timestamps: false },);User.belongsToMany(Profile, { through: User_Profile });Profile.belongsToMany(User, { through: User_Profile }); With this, we can now track an extra information at the through table, namely the selfGranted boolean. For example, when calling the user.addProfile() we can pass values for the extra columns using the through option. Example: const amidala = await User.create({ username: 'p4dm3', points: 1000 });const queen = await Profile.create({ name: 'Queen' });await amidala.addProfile(queen, { through: { selfGranted: false } });const result = await User.findOne({ where: { username: 'p4dm3' }, include: Profile,});console.log(result); Output: { "id": 4, "username": "p4dm3", "points": 1000, "profiles": [ { "id": 6, "name": "queen", "User_Profile": { "userId": 4, "profileId": 6, "selfGranted": false } } ]} You can create all relationship in single create call too. Example: const amidala = await User.create( { username: 'p4dm3', points: 1000, profiles: [ { name: 'Queen', User_Profile: { selfGranted: true, }, }, ], }, { include: Profile, },);const result = await User.findOne({ where: { username: 'p4dm3' }, include: Profile,});console.log(result); Output: { "id": 1, "username": "p4dm3", "points": 1000, "profiles": [ { "id": 1, "name": "Queen", "User_Profile": { "selfGranted": true, "userId": 1, "profileId": 1 } } ]} You probably noticed that the User_Profiles table does not have an id field. As mentioned above, it has a composite unique key instead. The name of this composite unique key is chosen automatically by Sequelize but can be customized with the uniqueKey option: User.belongsToMany(Profile, { through: User_Profiles, uniqueKey: 'my_custom_unique',}); Another possibility, if desired, is to force the through table to have a primary key just like other standard tables. To do this, simply define the primary key in the model: const User_Profile = sequelize.define( 'User_Profile', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false, }, selfGranted: DataTypes.BOOLEAN, }, { timestamps: false },);User.belongsToMany(Profile, { through: User_Profile });Profile.belongsToMany(User, { through: User_Profile }); The above will still create two columns userId and profileId, of course, but instead of setting up a composite unique key on them, the model will use its id column as primary key. Everything else will still work just fine. Through tables versus normal tables and the "Super Many-to-Many association" Now we will compare the usage of the last Many-to-Many setup shown above with the usual One-to-Many relationships, so that in the end we conclude with the concept of a "Super Many-to-Many relationship". Models recap (with minor rename) To make things easier to follow, let's rename our User_Profile model to grant. Note that everything works in the same way as before. Our models are: const User = sequelize.define( 'user', { username: DataTypes.STRING, points: DataTypes.INTEGER, }, { timestamps: false },);const Profile = sequelize.define( 'profile', { name: DataTypes.STRING, }, { timestamps: false },);const Grant = sequelize.define( 'grant', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false, }, selfGranted: DataTypes.BOOLEAN, }, { timestamps: false },); We established a Many-to-Many relationship between User and Profile using the Grant model as the through table: User.belongsToMany(Profile, { through: Grant });Profile.belongsToMany(User, { through: Grant }); This automatically added the columns userId and profileId to the Grant model. Note: As shown above, we have chosen to force the grant model to have a single primary key (called id, as usual). This is necessary for the Super Many-to-Many relationship that will be defined soon. Using One-to-Many relationships instead Instead of setting up the Many-to-Many relationship defined above, what if we did the following instead? // Setup a One-to-Many relationship between User and GrantUser.hasMany(Grant);Grant.belongsTo(User);// Also setup a One-to-Many relationship between Profile and GrantProfile.hasMany(Grant);Grant.belongsTo(Profile); The result is essentially the same! This is because User.hasMany(Grant) and Profile.hasMany(Grant) will automatically add the userId and profileId columns to Grant, respectively. This shows that one Many-to-Many relationship isn't very different from two One-to-Many relationships. The tables in the database look the same. The only difference is when you try to perform an eager load with Sequelize. // With the Many-to-Many approach, you can do:User.findAll({ include: Profile });Profile.findAll({ include: User });// However, you can't do:User.findAll({ include: Grant });Profile.findAll({ include: Grant });Grant.findAll({ include: User });Grant.findAll({ include: Profile });// On the other hand, with the double One-to-Many approach, you can do:User.findAll({ include: Grant });Profile.findAll({ include: Grant });Grant.findAll({ include: User });Grant.findAll({ include: Profile });// However, you can't do:User.findAll({ include: Profile });Profile.findAll({ include: User });// Although you can emulate those with nested includes, as follows:User.findAll({ include: { model: Grant, include: Profile, },}); // This emulates the User.findAll({ include: Profile }) однако результирующая структура объекта немного отличается. Исходная структура имеет вид user.profiles[].grant, а эмулированная структура имеет вид user.grants[].profiles[]. Лучшее из обоих миров: связь Super Many-to-Many Мы можем просто объединить оба подхода, показанных выше! // Связь Super Many-to-ManyUser.belongsToMany(Profile, { through: Grant });Profile.belongsToMany(User, { through: Grant });User.hasMany(Grant);Grant.belongsTo(User);Profile.hasMany(Grant);Grant.belongsTo(Profile); Таким образом, мы можем выполнять все виды жадной загрузки: // Всё это работает:User.findAll({ include: Profile });Profile.findAll({ include: User });User.findAll({ include: Grant });Profile.findAll({ include: Grant });Grant.findAll({ include: User });Grant.findAll({ include: Profile }); Мы можем даже выполнять все виды глубоко вложенных включений: User.findAll({ include: [ { model: Grant, include: [User, Profile], }, { model: Profile, include: { model: User, include: { model: Grant, include: [User, Profile], }, }, }, ],}); Псевдонимы и пользовательские имена ключей Как и в случае с другими связями, для связей Many-to-Many можно определять псевдонимы. Прежде чем продолжить, вспомните пример псевдонимов для belongsTo в руководстве по связям. Обратите внимание, что в том случае определение связи влияет как на способ выполнения включений (т.е. передачу имени связи), так и на имя, которое Sequelize выбирает для внешнего ключа (в том примере на модели Ship был создан leaderId). Определение псевдонима для связи belongsToMany также влияет на способ выполнения включений: Product.belongsToMany(Category, { as: 'groups', through: 'product_categories',});Category.belongsToMany(Product, { as: 'items', through: 'product_categories' });// [...]await Product.findAll({ include: Category }); // Это не работаетawait Product.findAll({ // Это работает, передаём псевдоним include: { model: Category, as: 'groups', },});await Product.findAll({ include: 'groups' }); // Это тоже работает Однако определение псевдонима здесь никак не связано с именами внешних ключей. Имена обоих внешних ключей, созданных в through-таблице, по-прежнему конструируются Sequelize на основе имён связываемых моделей. Это легко увидеть, изучив сгенерированный SQL для through-таблицы в примере выше: CREATE TABLE IF NOT EXISTS product_categories ( createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL, productId INTEGER NOT NULL REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE, categoryId INTEGER NOT NULL REFERENCES categories (id) ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY (productId, categoryId)); Видно, что внешние ключи — это productId и categoryId. Чтобы изменить эти имена, Sequelize принимает опции foreignKey и otherKey соответственно (то есть foreignKey задаёт ключ для исходной модели в сквозной связи, а otherKey — для целевой модели): Product.belongsToMany(Category, { through: 'product_categories', foreignKey: 'objectId', // заменяет productId otherKey: 'typeId', // заменяет categoryId});Category.belongsToMany(Product, { through: 'product_categories', foreignKey: 'typeId', // заменяет categoryId otherKey: 'objectId', // заменяет productId}); Сгенерированный SQL: CREATE TABLE IF NOT EXISTS product_categories ( createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL, objectId INTEGER NOT NULL REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE, typeId INTEGER NOT NULL REFERENCES categories (id) ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY (objectId, typeId)); As shown above, when you define a Many-to-Many relationship with two belongsToMany calls (which is the standard way), you should provide the foreignKey and otherKey options appropriately in both calls. If you pass these options in only one of the calls, the Sequelize behavior will be unreliable. Self-references Sequelize supports self-referential Many-to-Many relationships, intuitively: Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' });// This will create the table PersonChildren which stores the ids of the objects. Specifying attributes from the through table By default, when eager loading a many-to-many relationship, Sequelize will return data in the following structure (based on the first example in this guide): // User.findOne({ include: Profile }){ "id": 4, "username": "p4dm3", "points": 1000, "profiles": [ { "id": 6, "name": "queen", "grant": { "userId": 4, "profileId": 6, "selfGranted": false } } ]} Notice that the outer object is an User, which has a field called profiles, which is a Profile array, such that each Profile comes with an extra field called grant which is a Grant instance. This is the default structure created by Sequelize when eager loading from a Many-to-Many relationship. However, if you want only some of the attributes of the through table, you can provide an array with the attributes you want in the attributes option. For example, if you only want the selfGranted attribute from the through table: User.findOne({ include: { model: Profile, through: { attributes: ['selfGranted'], }, },}); Output: { "id": 4, "username": "p4dm3", "points": 1000, "profiles": [ { "id": 6, "name": "queen", "grant": { "selfGranted": false } } ]} If you don't want the nested grant field at all, use attributes: []: User.findOne({ include: { model: Profile, through: { attributes: [], }, },}); Output: { "id": 4, "username": "p4dm3", "points": 1000, "profiles": [ { "id": 6, "name": "queen" } ]} If you are using mixins (such as user.getProfiles()) instead of finder methods (such as User.findAll()), you have to use the joinTableAttributes option instead: someUser.getProfiles({ joinTableAttributes: ['selfGranted'] }); Output: [ { "id": 6, "name": "queen", "grant": { "selfGranted": false } }] Many-to-many-to-many relationships and beyond Consider you are trying to model a game championship. There are players and teams. Teams play games. However, players can change teams in the middle of the championship (but not in the middle of a game). So, given one specific game, there are certain teams participating in that game, and each of these teams has a set of players (for that game). So we start by defining the three relevant models: const Player = sequelize.define('Player', { username: DataTypes.STRING });const Team = sequelize.define('Team', { name: DataTypes.STRING });const Game = sequelize.define('Game', { name: DataTypes.STRING }); Now, the question is: how to associate them? First, we note that: One game has many teams associated to it (the ones that are playing that game); One team may have participated in many games. The above observations show that we need a Many-to-Many relationship between Game and Team. Let's use the Super Many-to-Many relationship as explained earlier in this guide: // Super Many-to-Many relationship between Game and Teamconst 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); The part about players is trickier. We note that the set of players that form a team depends not only on the team (obviously), but also on which game is being considered. Therefore, we don't want a Many-to-Many relationship between Player and Team. We also don't want a Many-to-Many relationship between Player and Game. Instead of associating a Player to any of those models, what we need is an association between a Player and something like a "team-game pair constraint", since it is the pair (team plus game) that defines which players belong there. So what we are looking for turns out to be precisely the junction model, GameTeam, itself! And, we note that, since a given game-team pair specifies many players, and on the other hand that the same player can participate of many game-team pairs, we need a Many-to-Many relationship between Player and GameTeam! To provide the greatest flexibility, let's use the Super Many-to-Many relationship construction here again: // Super Many-to-Many relationship between Player and GameTeamconst 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); The above associations achieve precisely what we want. Here is a full runnable example of this: 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 Teamconst 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 GameTeamconst 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 // in several ways, such as calling .setTeams для каждой игры. Однако для // краткости мы будем использовать прямые create вызовы, обращаясь напрямую // к нужным нам ID. Мы знаем, что ID выдаются по порядку начиная с 1. await GameTeam.bulkCreate([ { GameId: 1, TeamId: 1 }, // эта GameTeam получит id 1 { GameId: 1, TeamId: 2 }, // эта GameTeam получит id 2 { GameId: 2, TeamId: 1 }, // эта GameTeam получит id 3 { GameId: 2, TeamId: 3 }, // эта GameTeam получит id 4 { GameId: 3, TeamId: 2 }, // эта GameTeam получит id 5 { GameId: 3, TeamId: 3 }, // эта GameTeam получит id 6 ]); // Теперь укажем игроков. // Для краткости сделаем это только для второй игры (Winter Showdown). // Допустим, s0me0ne и greenhead играли за The Martians, а // not_spock и bowl_of_petunias играли за The Plutonians: await PlayerGameTeam.bulkCreate([ // В 'Winter Showdown' (т.е. GameTeamIds 3 и 4): { PlayerId: 1, GameTeamId: 3 }, // s0me0ne играл за The Martians { PlayerId: 3, GameTeamId: 3 }, // greenhead играл за The Martians { PlayerId: 4, GameTeamId: 4 }, // not_spock играл за The Plutonians { PlayerId: 5, GameTeamId: 4 }, // bowl_of_petunias играл за The Plutonians ]); // Теперь мы можем делать запросы! const game = await Game.findOne({ where: { name: 'Winter Showdown', }, include: { model: GameTeam, include: [ { model: Player, through: { attributes: [] }, // Скрыть нежелательный PlayerGameTeam вложенный объект из результатов }, Team, ], }, }); console.log(Found game: "${game.name}"); for (let i = 0; i < game.GameTeams.length; i++) { const team = game.GameTeams[i].Team; const players = game.GameTeams[i].Players; console.log(- Team "${team.name}" played game "${game.name}" with the following players:); console.log(players.map(p => --- ${p.username}).join('\n')); }})(); Вывод: Найдена игра: "Winter Showdown"- Команда "The Martians" играла в игру "Winter Showdown" со следующими игроками:--- s0me0ne--- greenhead- Команда "The Plutonians" играла в игру "Winter Showdown" со следующими игроками:--- not_spock--- bowl_of_petunias Итак, вот как мы можем реализовать связь многие-ко-многим-ко-многим между тремя моделями в Sequelize, используя технику Super Many-to-Many! Эту идею можно применять рекурсивно для ещё более сложных связей многие-ко-многим-...-ко-многим (хотя в какой-то момент запросы могут стать медленными).
User
Pattern 7: Пример:
await User.sync({ force: true });console.log('The table for the User model was just (re)created!');
Pattern 8: Вы можете использовать sequelize.sync() для автоматической синхронизации всех моделей. Пример:
sequelize.sync()
Примеры шаблонов кода
Пример 1 (css):
/* ... */ { username: { type: DataTypes.TEXT, allowNull: false, unique: true },} /* ... */
Пример 2 (javascript):
const jane = User.build({ name: 'Jane' });
console.log(jane instanceof User); // trueconsole.log(jane.name); // "Jane"
Пример 3 (sql):
const [results, metadata] = await sequelize.query('UPDATE users SET y = 42 WHERE x = 12');// Results will be an empty array and metadata will contain the number of affected rows.
Пример 4 (sql):
SELECT `id`, `status`, `createdAt`, `updatedAt`, `fooId`FROM `bars` AS `bar`WHERE `bar`.`status` = 'open' AND `bar`.`fooId` = 1;
Пример 5 (javascript):
const project = await Project.findByPk(123);if (project === null) { console.log('Not found!');} else { console.log(project instanceof Project); // true // Its primary key is 123}
Справочные файлы
Этот навык включает подробную документацию в references/:
- advanced.md - Расширенная документация
- associations.md - Документация по ассоциациям
- data_types.md - Документация по типам данных
- database.md - Документация по базе данных
- deployment.md - Документация по развертыванию
- getting_started.md - Документация по началу работы
- migrations.md - Документация по миграциям
- models.md - Документация по моделям
- other.md - Прочая документация
- querying.md - Документация по запросам
- typescript.md - Документация по Typescript
Используйте view для чтения конкретных справочных файлов, когда требуется подробная информация.
Работа с этим навыком
Для начинающих
Начните со справочных файлов getting_started или tutorials для изучения основополагающих концепций.
Для конкретных функций
Используйте соответствующий справочный файл категории (api, guides и т. д.) для получения подробной информации.
Для примеров кода
Раздел быстрого справочника выше содержит распространенные шаблоны, извлеченные из официальной документации.
Ресурсы
references/
Организованная документация, извлечённая из официальных источников. Эти файлы содержат:
- Подробные объяснения
- Примеры кода с аннотациями языков
- Ссылки на оригинальную документацию
- Оглавление для быстрой навигации
scripts/
Добавьте сюда вспомогательные скрипты для типовых задач автоматизации.
assets/
Добавьте сюда шаблоны, boilerplate или примеры проектов.
Примечания
- Этот навык был автоматически сгенерирован из официальной документации
- Справочные файлы сохраняют структуру и примеры из исходных документов
- Примеры кода включают определение языка для лучшей подсветки синтаксиса
- Паттерны быстрого справочника извлечены из типовых примеров использования в документации
Обновление
Чтобы обновить этот навык с актуальной документацией:
- Повторно запустите scraper с той же конфигурацией
- Навык будет пересобран с последней информацией
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: sequelize-patterns](https://darkplay.ru/ai/skills/joneqian-claude-skills-suite-sequelize-patterns)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
Go Revieweraffaan-m · Ревьюер кода Go: идиоматичность, конкурентность, обработка ошибок и производительность.
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
Opensource Sanitizeraffaan-m · Проверяет open-source форк на утечки секретов, PII и опасные файлы перед релизом.Лучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachatЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirton