123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659 |
- 'use strict';
- const range = require('lodash/range');
- const { expect } = require('chai');
- const { DataTypes, Op, Sequelize } = require('@sequelize/core');
- const dayjs = require('dayjs');
- const sinon = require('sinon');
- const assert = require('node:assert');
- const {
- allowDeprecationsInSuite,
- createSequelizeInstance,
- createSingleTransactionalTestSequelizeInstance,
- destroySequelizeAfterTest,
- getTestDialect,
- sequelize: current,
- } = require('../support');
- const dialectName = getTestDialect();
- describe('HasMany', () => {
- describe('Model.associations', () => {
- it('should store all assocations when associting to the same table multiple times', function () {
- const User = this.sequelize.define('User', {});
- const Group = this.sequelize.define('Group', {});
- Group.hasMany(User);
- Group.hasMany(User, {
- foreignKey: 'primaryGroupId',
- as: 'primaryUsers',
- inverse: { as: 'primaryGroup' },
- });
- Group.hasMany(User, {
- foreignKey: 'secondaryGroupId',
- as: 'secondaryUsers',
- inverse: { as: 'secondaryGroup' },
- });
- expect(Object.keys(Group.associations)).to.deep.equal([
- 'users',
- 'primaryUsers',
- 'secondaryUsers',
- ]);
- });
- });
- describe('count', () => {
- it('should not fail due to ambiguous field', async function () {
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- const Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- active: DataTypes.BOOLEAN,
- });
- User.hasMany(Task);
- const subtasks = Task.hasMany(Task, { as: 'subtasks', inverse: { as: 'supertask' } });
- await this.sequelize.sync({ force: true });
- const user0 = await User.create(
- {
- username: 'John',
- tasks: [
- {
- title: 'Get rich',
- active: true,
- },
- ],
- },
- {
- include: [Task],
- },
- );
- await Promise.all([
- user0.get('tasks')[0].createSubtask({ title: 'Make a startup', active: false }),
- user0.get('tasks')[0].createSubtask({ title: 'Engage rock stars', active: true }),
- ]);
- const user = user0;
- await expect(
- user.countTasks({
- attributes: [Task.primaryKeyField, 'title'],
- include: [
- {
- attributes: [],
- association: subtasks,
- where: {
- active: true,
- },
- },
- ],
- group: this.sequelize.col(`${Task.name}.${Task.primaryKeyField}`),
- }),
- ).to.eventually.equal(1);
- });
- });
- describe('get', () => {
- if (current.dialect.supports.groupedLimit) {
- describe('multiple', () => {
- it('should fetch associations for multiple instances', async function () {
- const User = this.sequelize.define('User', {});
- const Task = this.sequelize.define('Task', {});
- User.Tasks = User.hasMany(Task, { as: 'tasks' });
- await this.sequelize.sync({ force: true });
- const users = await Promise.all([
- User.create(
- {
- id: 1,
- tasks: [{}, {}, {}],
- },
- {
- include: [User.Tasks],
- },
- ),
- User.create(
- {
- id: 2,
- tasks: [{}],
- },
- {
- include: [User.Tasks],
- },
- ),
- User.create({
- id: 3,
- }),
- ]);
- const result = await User.Tasks.get(users);
- expect(result.get(users[0].id).length).to.equal(3);
- expect(result.get(users[1].id).length).to.equal(1);
- expect(result.get(users[2].id).length).to.equal(0);
- });
- it('should fetch associations for multiple instances with limit and order', async function () {
- const User = this.sequelize.define('User', {});
- const Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- });
- User.Tasks = User.hasMany(Task, { as: 'tasks' });
- await this.sequelize.sync({ force: true });
- const users = await Promise.all([
- User.create(
- {
- tasks: [{ title: 'b' }, { title: 'd' }, { title: 'c' }, { title: 'a' }],
- },
- {
- include: [User.Tasks],
- },
- ),
- User.create(
- {
- tasks: [{ title: 'a' }, { title: 'c' }, { title: 'b' }],
- },
- {
- include: [User.Tasks],
- },
- ),
- ]);
- const result = await User.Tasks.get(users, {
- limit: 2,
- order: [['title', 'ASC']],
- });
- expect(result.get(users[0].id).length).to.equal(2);
- expect(result.get(users[0].id)[0].title).to.equal('a');
- expect(result.get(users[0].id)[1].title).to.equal('b');
- expect(result.get(users[1].id).length).to.equal(2);
- expect(result.get(users[1].id)[0].title).to.equal('a');
- expect(result.get(users[1].id)[1].title).to.equal('b');
- });
- it('should fetch multiple layers of associations with limit and order with separate=true', async function () {
- const User = this.sequelize.define('User', {});
- const Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- });
- const SubTask = this.sequelize.define('SubTask', {
- title: DataTypes.STRING,
- });
- User.Tasks = User.hasMany(Task, { as: 'tasks' });
- Task.SubTasks = Task.hasMany(SubTask, { as: 'subtasks' });
- await this.sequelize.sync({ force: true });
- await Promise.all([
- User.create(
- {
- id: 1,
- tasks: [
- {
- title: 'b',
- subtasks: [{ title: 'c' }, { title: 'a' }],
- },
- { title: 'd' },
- {
- title: 'c',
- subtasks: [{ title: 'b' }, { title: 'a' }, { title: 'c' }],
- },
- {
- title: 'a',
- subtasks: [{ title: 'c' }, { title: 'a' }, { title: 'b' }],
- },
- ],
- },
- {
- include: [{ association: User.Tasks, include: [Task.SubTasks] }],
- },
- ),
- User.create(
- {
- id: 2,
- tasks: [
- {
- title: 'a',
- subtasks: [{ title: 'b' }, { title: 'a' }, { title: 'c' }],
- },
- {
- title: 'c',
- subtasks: [{ title: 'a' }],
- },
- {
- title: 'b',
- subtasks: [{ title: 'a' }, { title: 'b' }],
- },
- ],
- },
- {
- include: [{ association: User.Tasks, include: [Task.SubTasks] }],
- },
- ),
- ]);
- const users = await User.findAll({
- include: [
- {
- association: User.Tasks,
- limit: 2,
- order: [['title', 'ASC']],
- separate: true,
- as: 'tasks',
- include: [
- {
- association: Task.SubTasks,
- order: [['title', 'DESC']],
- separate: true,
- as: 'subtasks',
- },
- ],
- },
- ],
- order: [['id', 'ASC']],
- });
- expect(users[0].tasks.length).to.equal(2);
- expect(users[0].tasks[0].title).to.equal('a');
- expect(users[0].tasks[0].subtasks.length).to.equal(3);
- expect(users[0].tasks[0].subtasks[0].title).to.equal('c');
- expect(users[0].tasks[0].subtasks[1].title).to.equal('b');
- expect(users[0].tasks[0].subtasks[2].title).to.equal('a');
- expect(users[0].tasks[1].title).to.equal('b');
- expect(users[0].tasks[1].subtasks.length).to.equal(2);
- expect(users[0].tasks[1].subtasks[0].title).to.equal('c');
- expect(users[0].tasks[1].subtasks[1].title).to.equal('a');
- expect(users[1].tasks.length).to.equal(2);
- expect(users[1].tasks[0].title).to.equal('a');
- expect(users[1].tasks[0].subtasks.length).to.equal(3);
- expect(users[1].tasks[0].subtasks[0].title).to.equal('c');
- expect(users[1].tasks[0].subtasks[1].title).to.equal('b');
- expect(users[1].tasks[0].subtasks[2].title).to.equal('a');
- expect(users[1].tasks[1].title).to.equal('b');
- expect(users[1].tasks[1].subtasks.length).to.equal(2);
- expect(users[1].tasks[1].subtasks[0].title).to.equal('b');
- expect(users[1].tasks[1].subtasks[1].title).to.equal('a');
- });
- it('should fetch associations for multiple instances with limit and order and a belongsTo relation', async function () {
- const User = this.sequelize.define('User', {});
- const Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- categoryId: {
- type: DataTypes.INTEGER,
- field: 'category_id',
- },
- });
- const Category = this.sequelize.define('Category', {});
- User.Tasks = User.hasMany(Task, { as: 'tasks' });
- Task.Category = Task.belongsTo(Category, { as: 'category', foreignKey: 'categoryId' });
- await this.sequelize.sync({ force: true });
- const users = await Promise.all([
- User.create(
- {
- tasks: [
- { title: 'b', category: {} },
- { title: 'd', category: {} },
- { title: 'c', category: {} },
- { title: 'a', category: {} },
- ],
- },
- {
- include: [{ association: User.Tasks, include: [Task.Category] }],
- },
- ),
- User.create(
- {
- tasks: [
- { title: 'a', category: {} },
- { title: 'c', category: {} },
- { title: 'b', category: {} },
- ],
- },
- {
- include: [{ association: User.Tasks, include: [Task.Category] }],
- },
- ),
- ]);
- const result = await User.Tasks.get(users, {
- limit: 2,
- order: [['title', 'ASC']],
- include: [Task.Category],
- });
- expect(result.get(users[0].id).length).to.equal(2);
- expect(result.get(users[0].id)[0].title).to.equal('a');
- expect(result.get(users[0].id)[0].category).to.be.ok;
- expect(result.get(users[0].id)[1].title).to.equal('b');
- expect(result.get(users[0].id)[1].category).to.be.ok;
- expect(result.get(users[1].id).length).to.equal(2);
- expect(result.get(users[1].id)[0].title).to.equal('a');
- expect(result.get(users[1].id)[0].category).to.be.ok;
- expect(result.get(users[1].id)[1].title).to.equal('b');
- expect(result.get(users[1].id)[1].category).to.be.ok;
- });
- it('supports schemas', async function () {
- const User = this.sequelize.define('User', {}).withSchema('work');
- const Task = this.sequelize
- .define('Task', {
- title: DataTypes.STRING,
- })
- .withSchema('work');
- const SubTask = this.sequelize
- .define('SubTask', {
- title: DataTypes.STRING,
- })
- .withSchema('work');
- User.Tasks = User.hasMany(Task, { as: 'tasks' });
- Task.SubTasks = Task.hasMany(SubTask, { as: 'subtasks' });
- await this.sequelize.createSchema('work');
- await User.sync({ force: true });
- await Task.sync({ force: true });
- await SubTask.sync({ force: true });
- await Promise.all([
- User.create(
- {
- id: 1,
- tasks: [
- {
- title: 'b',
- subtasks: [{ title: 'c' }, { title: 'a' }],
- },
- { title: 'd' },
- {
- title: 'c',
- subtasks: [{ title: 'b' }, { title: 'a' }, { title: 'c' }],
- },
- {
- title: 'a',
- subtasks: [{ title: 'c' }, { title: 'a' }, { title: 'b' }],
- },
- ],
- },
- {
- include: [{ association: User.Tasks, include: [Task.SubTasks] }],
- },
- ),
- User.create(
- {
- id: 2,
- tasks: [
- {
- title: 'a',
- subtasks: [{ title: 'b' }, { title: 'a' }, { title: 'c' }],
- },
- {
- title: 'c',
- subtasks: [{ title: 'a' }],
- },
- {
- title: 'b',
- subtasks: [{ title: 'a' }, { title: 'b' }],
- },
- ],
- },
- {
- include: [{ association: User.Tasks, include: [Task.SubTasks] }],
- },
- ),
- ]);
- const users = await User.findAll({
- include: [
- {
- association: User.Tasks,
- limit: 2,
- order: [['title', 'ASC']],
- separate: true,
- as: 'tasks',
- include: [
- {
- association: Task.SubTasks,
- order: [['title', 'DESC']],
- separate: true,
- as: 'subtasks',
- },
- ],
- },
- ],
- order: [['id', 'ASC']],
- });
- expect(users[0].tasks.length).to.equal(2);
- expect(users[0].tasks[0].title).to.equal('a');
- expect(users[0].tasks[0].subtasks.length).to.equal(3);
- expect(users[0].tasks[0].subtasks[0].title).to.equal('c');
- expect(users[0].tasks[0].subtasks[1].title).to.equal('b');
- expect(users[0].tasks[0].subtasks[2].title).to.equal('a');
- expect(users[0].tasks[1].title).to.equal('b');
- expect(users[0].tasks[1].subtasks.length).to.equal(2);
- expect(users[0].tasks[1].subtasks[0].title).to.equal('c');
- expect(users[0].tasks[1].subtasks[1].title).to.equal('a');
- expect(users[1].tasks.length).to.equal(2);
- expect(users[1].tasks[0].title).to.equal('a');
- expect(users[1].tasks[0].subtasks.length).to.equal(3);
- expect(users[1].tasks[0].subtasks[0].title).to.equal('c');
- expect(users[1].tasks[0].subtasks[1].title).to.equal('b');
- expect(users[1].tasks[0].subtasks[2].title).to.equal('a');
- expect(users[1].tasks[1].title).to.equal('b');
- expect(users[1].tasks[1].subtasks.length).to.equal(2);
- expect(users[1].tasks[1].subtasks[0].title).to.equal('b');
- expect(users[1].tasks[1].subtasks[1].title).to.equal('a');
- await this.sequelize.queryInterface.dropAllTables({ schema: 'work' });
- await this.sequelize.dropSchema('work');
- const schemas = await this.sequelize.queryInterface.listSchemas();
- expect(schemas).to.not.include('work');
- });
- });
- }
- });
- describe('(1:N)', () => {
- describe('hasAssociation', () => {
- beforeEach(function () {
- this.Article = this.sequelize.define('Article', {
- pk: {
- type: DataTypes.INTEGER,
- autoIncrement: true,
- primaryKey: true,
- },
- title: DataTypes.STRING,
- });
- this.Label = this.sequelize.define('Label', {
- key: {
- type: DataTypes.INTEGER,
- autoIncrement: true,
- primaryKey: true,
- },
- text: DataTypes.STRING,
- });
- this.Article.hasMany(this.Label);
- return this.sequelize.sync({ force: true });
- });
- it('should only generate one set of foreignKeys', function () {
- this.Article = this.sequelize.define(
- 'Article',
- { title: DataTypes.STRING },
- { timestamps: false },
- );
- this.Label = this.sequelize.define(
- 'Label',
- { text: DataTypes.STRING },
- { timestamps: false },
- );
- this.Label.belongsTo(this.Article);
- this.Article.hasMany(this.Label);
- expect(Object.keys(this.Label.getAttributes())).to.deep.equal(['id', 'text', 'articleId']);
- });
- if (current.dialect.supports.transactions) {
- it('supports transactions', async function () {
- const sequelize = await createSingleTransactionalTestSequelizeInstance(this.sequelize);
- const Article = sequelize.define('Article', { title: DataTypes.STRING });
- const Label = sequelize.define('Label', { text: DataTypes.STRING });
- Article.hasMany(Label);
- await sequelize.sync({ force: true });
- const [article, label] = await Promise.all([
- Article.create({ title: 'foo' }),
- Label.create({ text: 'bar' }),
- ]);
- const t = await sequelize.startUnmanagedTransaction();
- await article.setLabels([label], { transaction: t });
- const articles0 = await Article.findAll({ transaction: t });
- const hasLabel0 = await articles0[0].hasLabel(label);
- expect(hasLabel0).to.be.false;
- const articles = await Article.findAll({ transaction: t });
- const hasLabel = await articles[0].hasLabel(label, { transaction: t });
- expect(hasLabel).to.be.true;
- await t.rollback();
- });
- }
- it('does not have any labels assigned to it initially', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- const [hasLabel1, hasLabel2] = await Promise.all([
- article.hasLabel(label1),
- article.hasLabel(label2),
- ]);
- expect(hasLabel1).to.be.false;
- expect(hasLabel2).to.be.false;
- });
- it('answers true if the label has been assigned', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- await article.addLabel(label1);
- const [hasLabel1, hasLabel2] = await Promise.all([
- article.hasLabel(label1),
- article.hasLabel(label2),
- ]);
- expect(hasLabel1).to.be.true;
- expect(hasLabel2).to.be.false;
- });
- it('answers correctly if the label has been assigned when passing a primary key instead of an object', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- await article.addLabel(label1);
- const [hasLabel1, hasLabel2] = await Promise.all([
- article.hasLabel(label1[this.Label.primaryKeyAttribute]),
- article.hasLabel(label2[this.Label.primaryKeyAttribute]),
- ]);
- expect(hasLabel1).to.be.true;
- expect(hasLabel2).to.be.false;
- });
- });
- describe('hasAssociations', () => {
- beforeEach(function () {
- this.Article = this.sequelize.define('Article', {
- pk: {
- type: DataTypes.INTEGER,
- autoIncrement: true,
- primaryKey: true,
- },
- title: DataTypes.STRING,
- });
- this.Label = this.sequelize.define('Label', {
- key: {
- type: DataTypes.INTEGER,
- autoIncrement: true,
- primaryKey: true,
- },
- text: DataTypes.STRING,
- });
- this.Article.hasMany(this.Label);
- return this.sequelize.sync({ force: true });
- });
- if (current.dialect.supports.transactions) {
- it('supports transactions', async function () {
- const sequelize = await createSingleTransactionalTestSequelizeInstance(this.sequelize);
- const Article = sequelize.define('Article', { title: DataTypes.STRING });
- const Label = sequelize.define('Label', { text: DataTypes.STRING });
- Article.hasMany(Label);
- await sequelize.sync({ force: true });
- const [article, label] = await Promise.all([
- Article.create({ title: 'foo' }),
- Label.create({ text: 'bar' }),
- ]);
- const t = await sequelize.startUnmanagedTransaction();
- await article.setLabels([label], { transaction: t });
- const articles = await Article.findAll({ transaction: t });
- const [hasLabel1, hasLabel2] = await Promise.all([
- articles[0].hasLabels([label]),
- articles[0].hasLabels([label], { transaction: t }),
- ]);
- expect(hasLabel1).to.be.false;
- expect(hasLabel2).to.be.true;
- await t.rollback();
- });
- }
- it('answers false if only some labels have been assigned', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- await article.addLabel(label1);
- const result = await article.hasLabels([label1, label2]);
- expect(result).to.be.false;
- });
- it('answers false if only some labels have been assigned when passing a primary key instead of an object', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- await article.addLabel(label1);
- const result = await article.hasLabels([
- label1[this.Label.primaryKeyAttribute],
- label2[this.Label.primaryKeyAttribute],
- ]);
- expect(result).to.be.false;
- });
- it('answers true if all label have been assigned', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- await article.setLabels([label1, label2]);
- const result = await article.hasLabels([label1, label2]);
- expect(result).to.be.true;
- });
- it('answers true if all label have been assigned when passing a primary key instead of an object', async function () {
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness' }),
- this.Label.create({ text: 'Epicness' }),
- ]);
- await article.setLabels([label1, label2]);
- const result = await article.hasLabels([
- label1[this.Label.primaryKeyAttribute],
- label2[this.Label.primaryKeyAttribute],
- ]);
- expect(result).to.be.true;
- });
- });
- describe('addAssociations', () => {
- if (current.dialect.supports.transactions) {
- it('supports transactions', async function () {
- const sequelize = await createSingleTransactionalTestSequelizeInstance(this.sequelize);
- const Article = sequelize.define('Article', { title: DataTypes.STRING });
- const Label = sequelize.define('Label', { text: DataTypes.STRING });
- Article.hasMany(Label);
- await sequelize.sync({ force: true });
- const [article, label] = await Promise.all([
- Article.create({ title: 'foo' }),
- Label.create({ text: 'bar' }),
- ]);
- const t = await sequelize.startUnmanagedTransaction();
- await article.addLabel(label, { transaction: t });
- const labels0 = await Label.findAll({
- where: { articleId: article.id },
- transaction: undefined,
- });
- expect(labels0.length).to.equal(0);
- const labels = await Label.findAll({ where: { articleId: article.id }, transaction: t });
- expect(labels.length).to.equal(1);
- await t.rollback();
- });
- }
- it('supports passing the primary key instead of an object', async function () {
- const Article = this.sequelize.define('Article', { title: DataTypes.STRING });
- const Label = this.sequelize.define('Label', { text: DataTypes.STRING });
- Article.hasMany(Label);
- await this.sequelize.sync({ force: true });
- const [article, label] = await Promise.all([
- Article.create({}),
- Label.create({ text: 'label one' }),
- ]);
- await article.addLabel(label.id);
- const labels = await article.getLabels();
- expect(labels[0].text).to.equal('label one'); // Make sure that we didn't modify one of the other attributes while building / saving a new instance
- });
- });
- describe('addMultipleAssociations', () => {
- it('adds associations without removing the current ones', async function () {
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- Task.hasMany(User);
- await this.sequelize.sync({ force: true });
- await User.bulkCreate([{ username: 'foo ' }, { username: 'bar ' }, { username: 'baz ' }]);
- const task = await Task.create({ title: 'task' });
- const users0 = await User.findAll();
- const users = users0;
- await task.setUsers([users0[0]]);
- await task.addUsers([users[1], users[2]]);
- expect(await task.getUsers()).to.have.length(3);
- });
- it('handles decent sized bulk creates', async function () {
- const User = this.sequelize.define('User', {
- username: DataTypes.STRING,
- num: DataTypes.INTEGER,
- status: DataTypes.STRING,
- });
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- Task.hasMany(User);
- await this.sequelize.sync({ force: true });
- const users0 = range(1000).map(i => ({ username: `user${i}`, num: i, status: 'live' }));
- await User.bulkCreate(users0);
- await Task.create({ title: 'task' });
- const users = await User.findAll();
- expect(users).to.have.length(1000);
- });
- });
- it('clears associations when passing null to the set-method with omitNull set to true', async () => {
- const sequelize = createSequelizeInstance({
- omitNull: true,
- });
- destroySequelizeAfterTest(sequelize);
- const User = sequelize.define('User', { username: DataTypes.STRING });
- const Task = sequelize.define('Task', { title: DataTypes.STRING });
- Task.hasMany(User);
- await sequelize.sync({ force: true });
- const user = await User.create({ username: 'foo' });
- const task = await Task.create({ title: 'task' });
- await task.setUsers([user]);
- expect(await task.getUsers()).to.have.length(1);
- await task.setUsers(null);
- expect(await task.getUsers()).to.have.length(0);
- });
- describe('createAssociations', () => {
- it('creates a new associated object', async function () {
- const Article = this.sequelize.define('Article', { title: DataTypes.STRING });
- const Label = this.sequelize.define('Label', { text: DataTypes.STRING });
- Article.hasMany(Label);
- await this.sequelize.sync({ force: true });
- const article0 = await Article.create({ title: 'foo' });
- await article0.createLabel({ text: 'bar' });
- const article = article0;
- const labels = await Label.findAll({ where: { articleId: article.id } });
- expect(labels.length).to.equal(1);
- });
- it('creates the object with the association directly', async function () {
- const spy = sinon.spy();
- const Article = this.sequelize.define('Article', {
- title: DataTypes.STRING,
- });
- const Label = this.sequelize.define('Label', {
- text: DataTypes.STRING,
- });
- Article.hasMany(Label);
- await this.sequelize.sync({ force: true });
- const article = await Article.create({ title: 'foo' });
- const label = await article.createLabel({ text: 'bar' }, { logging: spy });
- expect(spy.calledOnce).to.be.true;
- expect(label.articleId).to.equal(article.id);
- });
- if (current.dialect.supports.transactions) {
- it('supports transactions', async function () {
- const sequelize = await createSingleTransactionalTestSequelizeInstance(this.sequelize);
- const Article = sequelize.define('Article', { title: DataTypes.STRING });
- const Label = sequelize.define('Label', { text: DataTypes.STRING });
- Article.hasMany(Label);
- await sequelize.sync({ force: true });
- const article = await Article.create({ title: 'foo' });
- const t = await sequelize.startUnmanagedTransaction();
- await article.createLabel({ text: 'bar' }, { transaction: t });
- const labels1 = await Label.findAll();
- expect(labels1.length).to.equal(0);
- const labels0 = await Label.findAll({ where: { articleId: article.id } });
- expect(labels0.length).to.equal(0);
- const labels = await Label.findAll({ where: { articleId: article.id }, transaction: t });
- expect(labels.length).to.equal(1);
- await t.rollback();
- });
- }
- it('supports passing the field option', async function () {
- const Article = this.sequelize.define('Article', {
- title: DataTypes.STRING,
- });
- const Label = this.sequelize.define('Label', {
- text: DataTypes.STRING,
- });
- Article.hasMany(Label);
- await this.sequelize.sync({ force: true });
- const article0 = await Article.create();
- await article0.createLabel(
- {
- text: 'yolo',
- },
- {
- fields: ['text'],
- },
- );
- const article = article0;
- const labels = await article.getLabels();
- expect(labels.length).to.be.ok;
- });
- });
- describe('getting assocations with options', () => {
- beforeEach(async function () {
- this.User = this.sequelize.define('User', { username: DataTypes.STRING });
- this.Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- active: DataTypes.BOOLEAN,
- });
- this.User.hasMany(this.Task);
- await this.sequelize.sync({ force: true });
- const [john, task1, task2] = await Promise.all([
- this.User.create({ username: 'John' }),
- this.Task.create({ title: 'Get rich', active: true }),
- this.Task.create({ title: 'Die trying', active: false }),
- ]);
- return john.setTasks([task1, task2]);
- });
- it('should treat the where object of associations as a first class citizen', async function () {
- this.Article = this.sequelize.define('Article', {
- title: DataTypes.STRING,
- });
- this.Label = this.sequelize.define('Label', {
- text: DataTypes.STRING,
- until: DataTypes.DATE,
- });
- this.Article.hasMany(this.Label);
- await this.sequelize.sync({ force: true });
- const [article, label1, label2] = await Promise.all([
- this.Article.create({ title: 'Article' }),
- this.Label.create({ text: 'Awesomeness', until: '2014-01-01 01:00:00' }),
- this.Label.create({ text: 'Epicness', until: '2014-01-03 01:00:00' }),
- ]);
- await article.setLabels([label1, label2]);
- const labels = await article.getLabels({
- where: { until: { [Op.gt]: dayjs('2014-01-02').toDate() } },
- });
- expect(labels).to.be.instanceof(Array);
- expect(labels).to.have.length(1);
- expect(labels[0].text).to.equal('Epicness');
- });
- it('gets all associated objects when no options are passed', async function () {
- const john = await this.User.findOne({ where: { username: 'John' } });
- const tasks = await john.getTasks();
- expect(tasks).to.have.length(2);
- });
- it('only get objects that fulfill the options', async function () {
- const john = await this.User.findOne({ where: { username: 'John' } });
- const tasks = await john.getTasks({
- where: { active: true },
- limit: 10,
- order: [['id', 'DESC']],
- });
- expect(tasks).to.have.length(1);
- });
- });
- describe('countAssociations', () => {
- beforeEach(async function () {
- this.User = this.sequelize.define('User', { username: DataTypes.STRING });
- this.Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- active: DataTypes.BOOLEAN,
- });
- this.User.hasMany(this.Task, {
- foreignKey: 'userId',
- });
- await this.sequelize.sync({ force: true });
- const [john, task1, task2] = await Promise.all([
- this.User.create({ username: 'John' }),
- this.Task.create({ title: 'Get rich', active: true }),
- this.Task.create({ title: 'Die trying', active: false }),
- ]);
- this.user = john;
- return john.setTasks([task1, task2]);
- });
- it('should count all associations', async function () {
- await expect(this.user.countTasks({})).to.eventually.equal(2);
- });
- it('should count filtered associations', async function () {
- await expect(
- this.user.countTasks({
- where: {
- active: true,
- },
- }),
- ).to.eventually.equal(1);
- });
- it('should count scoped associations', async function () {
- this.User.hasMany(this.Task, {
- foreignKey: 'userId',
- as: 'activeTasks',
- inverse: {
- as: 'activeUsers',
- },
- scope: {
- active: true,
- },
- });
- await expect(this.user.countActiveTasks({})).to.eventually.equal(1);
- });
- });
- describe('thisAssociations', () => {
- it('should work with alias', async function () {
- const Person = this.sequelize.define('Group', {});
- Person.hasMany(Person, { as: 'Children', inverse: { as: 'parent' } });
- await this.sequelize.sync();
- });
- });
- });
- describe('foreign key constraints', () => {
- describe('1:m', () => {
- it('sets null by default', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task);
- await this.sequelize.sync({ force: true });
- const [user, task0] = await Promise.all([
- User.create({ username: 'foo' }),
- Task.create({ title: 'task' }),
- ]);
- await user.setTasks([task0]);
- await user.destroy();
- const task = await task0.reload();
- expect(task.userId).to.equal(null);
- });
- it('sets to CASCADE if allowNull: false', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task, { foreignKey: { allowNull: false } }); // defaults to CASCADE
- await this.sequelize.sync({ force: true });
- const user = await User.create({ username: 'foo' });
- await Task.create({ title: 'task', userId: user.id });
- await user.destroy();
- const tasks = await Task.findAll();
- expect(tasks).to.be.empty;
- });
- it('should be possible to remove all constraints', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task, { foreignKeyConstraints: false });
- await this.sequelize.sync({ force: true });
- const [user, task0] = await Promise.all([
- User.create({ username: 'foo' }),
- Task.create({ title: 'task' }),
- ]);
- const task = task0;
- await user.setTasks([task0]);
- await user.destroy();
- await task.reload();
- expect(task.userId).to.equal(user.id);
- });
- it('can cascade deletes', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task, { foreignKey: { onDelete: 'cascade' } });
- await this.sequelize.sync({ force: true });
- const [user, task] = await Promise.all([
- User.create({ username: 'foo' }),
- Task.create({ title: 'task' }),
- ]);
- await user.setTasks([task]);
- await user.destroy();
- const tasks = await Task.findAll();
- expect(tasks).to.have.length(0);
- });
- // NOTE: mssql does not support changing an autoincrement primary key
- if (!['mssql', 'db2', 'ibmi'].includes(dialectName)) {
- it('can cascade updates', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task, { foreignKey: { onUpdate: 'cascade' } });
- await this.sequelize.sync({ force: true });
- const [user0, task] = await Promise.all([
- User.create({ username: 'foo' }),
- Task.create({ title: 'task' }),
- ]);
- await user0.setTasks([task]);
- const user = user0;
- // Changing the id of a DAO requires a little dance since
- // the `UPDATE` query generated by `save()` uses `id` in the
- // `WHERE` clause
- const tableName = User.table;
- await user.sequelize.queryInterface.update(user, tableName, { id: 999 }, { id: user.id });
- const tasks = await Task.findAll();
- expect(tasks).to.have.length(1);
- expect(tasks[0].userId).to.equal(999);
- });
- }
- if (current.dialect.supports.constraints.restrict) {
- it('can restrict deletes', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task, { foreignKey: { onDelete: 'restrict' } });
- let tasks;
- await this.sequelize.sync({ force: true });
- const [user, task] = await Promise.all([
- User.create({ username: 'foo' }),
- Task.create({ title: 'task' }),
- ]);
- await user.setTasks([task]);
- try {
- tasks = await user.destroy();
- } catch (error) {
- if (!(error instanceof Sequelize.ForeignKeyConstraintError)) {
- throw error;
- }
- // Should fail due to FK violation
- tasks = await Task.findAll();
- }
- expect(tasks).to.have.length(1);
- });
- it('can restrict updates', async function () {
- const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
- const User = this.sequelize.define('User', { username: DataTypes.STRING });
- User.hasMany(Task, { foreignKey: { onUpdate: 'restrict' } });
- let tasks;
- await this.sequelize.sync({ force: true });
- const [user0, task] = await Promise.all([
- User.create({ username: 'foo' }),
- Task.create({ title: 'task' }),
- ]);
- await user0.setTasks([task]);
- const user = user0;
- // Changing the id of a DAO requires a little dance since
- // the `UPDATE` query generated by `save()` uses `id` in the
- // `WHERE` clause
- const tableName = User.table;
- try {
- tasks = await user.sequelize.queryInterface.update(
- user,
- tableName,
- { id: 999 },
- { id: user.id },
- );
- } catch (error) {
- if (!(error instanceof Sequelize.ForeignKeyConstraintError)) {
- throw error;
- }
- // Should fail due to FK violation
- tasks = await Task.findAll();
- }
- expect(tasks).to.have.length(1);
- });
- }
- });
- });
- describe('Association options', () => {
- allowDeprecationsInSuite(['SEQUELIZE0005']);
- it('should setup underscored field with foreign keys when using underscored', function () {
- const User = this.sequelize.define(
- 'User',
- { username: DataTypes.STRING },
- { underscored: true },
- );
- const Account = this.sequelize.define(
- 'Account',
- { name: DataTypes.STRING },
- { underscored: true },
- );
- User.hasMany(Account);
- expect(Account.getAttributes().userId).to.exist;
- expect(Account.getAttributes().userId.field).to.equal('user_id');
- });
- it('should use model name when using camelcase', function () {
- const User = this.sequelize.define(
- 'User',
- { username: DataTypes.STRING },
- { underscored: false },
- );
- const Account = this.sequelize.define(
- 'Account',
- { name: DataTypes.STRING },
- { underscored: false },
- );
- User.hasMany(Account);
- expect(Account.getAttributes().userId).to.exist;
- expect(Account.getAttributes().userId.field).to.equal('userId');
- });
- it('can specify data type for auto-generated relational keys', async function () {
- const User = this.sequelize.define('UserXYZ', { username: DataTypes.STRING });
- const dataTypes = [DataTypes.INTEGER, DataTypes.STRING];
- const Tasks = {};
- if (current.dialect.supports.dataTypes.BIGINT) {
- dataTypes.push(DataTypes.BIGINT);
- }
- for (const dataType of dataTypes) {
- const tableName = `TaskXYZ_${dataType.getDataTypeId()}`;
- Tasks[dataType] = this.sequelize.define(tableName, { title: DataTypes.STRING });
- User.hasMany(Tasks[dataType], {
- foreignKey: { name: 'userId', type: dataType },
- foreignKeyConstraints: false,
- });
- await Tasks[dataType].sync({ force: true });
- expect(Tasks[dataType].getAttributes().userId.type).to.be.an.instanceof(dataType);
- }
- });
- it('infers the foreignKey.type if none provided', async function () {
- const User = this.sequelize.define('User', {
- id: { type: DataTypes.STRING, primaryKey: true },
- username: DataTypes.STRING,
- });
- const Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- });
- User.hasMany(Task);
- await this.sequelize.sync({ force: true });
- expect(Task.getAttributes().userId.type instanceof DataTypes.STRING).to.be.ok;
- });
- describe('allows the user to provide an attribute definition object as foreignKey', () => {
- it('works with a column that hasnt been defined before', function () {
- const Task = this.sequelize.define('task', {});
- const User = this.sequelize.define('user', {});
- User.hasMany(Task, {
- foreignKey: {
- name: 'uid',
- allowNull: false,
- },
- });
- expect(Task.getAttributes().uid).to.be.ok;
- expect(Task.getAttributes().uid.allowNull).to.be.false;
- const targetTable = Task.getAttributes().uid.references.table;
- assert(typeof targetTable === 'object');
- expect(targetTable).to.deep.equal(User.table);
- expect(Task.getAttributes().uid.references.key).to.equal('id');
- });
- it('works when taking a column directly from the object', function () {
- const Project = this.sequelize.define('project', {
- user_id: {
- type: DataTypes.INTEGER,
- defaultValue: 42,
- },
- });
- const User = this.sequelize.define('user', {
- uid: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- },
- });
- User.hasMany(Project, { foreignKey: Project.getAttributes().user_id });
- expect(Project.getAttributes().user_id).to.be.ok;
- const targetTable = Project.getAttributes().user_id.references.table;
- assert(typeof targetTable === 'object');
- expect(targetTable).to.deep.equal(User.table);
- expect(Project.getAttributes().user_id.references.key).to.equal('uid');
- expect(Project.getAttributes().user_id.defaultValue).to.equal(42);
- });
- it('works when merging with an existing definition', function () {
- const Task = this.sequelize.define('task', {
- userId: {
- defaultValue: 42,
- type: DataTypes.INTEGER,
- },
- });
- const User = this.sequelize.define('user', {});
- User.hasMany(Task, { foreignKey: { allowNull: true } });
- expect(Task.getAttributes().userId).to.be.ok;
- expect(Task.getAttributes().userId.defaultValue).to.equal(42);
- expect(Task.getAttributes().userId.allowNull).to.be.ok;
- });
- });
- it('should throw an error if foreignKey and as result in a name clash', function () {
- const User = this.sequelize.define('user', {
- user: DataTypes.INTEGER,
- });
- expect(User.hasMany.bind(User, User, { as: 'user' })).to.throw(
- "Naming collision between attribute 'user' and association 'user' on model user. To remedy this, change the \"as\" options in your association definition",
- );
- });
- it('should ignore group from ancestor on deep separated query', async function () {
- const User = this.sequelize.define('user', {
- userId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
- username: DataTypes.STRING,
- });
- const Task = this.sequelize.define('task', {
- taskId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
- title: DataTypes.STRING,
- });
- const Job = this.sequelize.define('job', {
- jobId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
- title: DataTypes.STRING,
- });
- Task.hasMany(Job, { foreignKey: 'taskId' });
- User.hasMany(Task, { foreignKey: 'userId' });
- await this.sequelize.sync({ force: true });
- await User.create(
- {
- username: 'John Doe',
- tasks: [
- { title: 'Task #1', jobs: [{ title: 'Job #1' }, { title: 'Job #2' }] },
- { title: 'Task #2', jobs: [{ title: 'Job #3' }, { title: 'Job #4' }] },
- ],
- },
- { include: [{ model: Task, include: [Job] }] },
- );
- const { count, rows } = await User.findAndCountAll({
- attributes: ['userId'],
- include: [{ model: Task, separate: true, include: [{ model: Job, separate: true }] }],
- group: [['userId']],
- });
- expect(count.length).to.equal(1);
- expect(count).to.deep.equal([{ userId: 1, count: 1 }]);
- expect(rows[0].tasks[0].jobs.length).to.equal(2);
- });
- });
- describe('sourceKey', () => {
- beforeEach(function () {
- const User = this.sequelize.define(
- 'UserXYZ',
- { username: DataTypes.STRING, email: { type: DataTypes.STRING, allowNull: false } },
- { indexes: [{ fields: ['email'], unique: true }] },
- );
- const Task = this.sequelize.define('TaskXYZ', {
- title: DataTypes.STRING,
- userEmail: { type: DataTypes.STRING, field: 'user_email_xyz' },
- });
- User.hasMany(Task, { foreignKey: 'userEmail', sourceKey: 'email', as: 'tasks' });
- this.User = User;
- this.Task = Task;
- return this.sequelize.sync({ force: true });
- });
- it('should use sourceKey', async function () {
- const User = this.User;
- const Task = this.Task;
- const user = await User.create({ username: 'John', email: 'john@example.com' });
- await Task.create({ title: 'Fix PR', userEmail: 'john@example.com' });
- const tasks = await user.getTasks();
- expect(tasks.length).to.equal(1);
- expect(tasks[0].title).to.equal('Fix PR');
- });
- it('should count related records', async function () {
- const User = this.User;
- const Task = this.Task;
- const user = await User.create({ username: 'John', email: 'john@example.com' });
- await Task.create({ title: 'Fix PR', userEmail: 'john@example.com' });
- const tasksCount = await user.countTasks();
- expect(tasksCount).to.equal(1);
- });
- it('should set right field when add relative', async function () {
- const User = this.User;
- const Task = this.Task;
- const user = await User.create({ username: 'John', email: 'john@example.com' });
- const task = await Task.create({ title: 'Fix PR' });
- await user.addTask(task);
- const hasTask = await user.hasTask(task.id);
- expect(hasTask).to.be.true;
- });
- it('should create with nested associated models', async function () {
- const User = this.User;
- const values = {
- username: 'John',
- email: 'john@example.com',
- tasks: [{ title: 'Fix new PR' }],
- };
- const user0 = await User.create(values, { include: ['tasks'] });
- // Make sure tasks are defined for created user
- expect(user0).to.have.property('tasks');
- expect(user0.tasks).to.be.an('array');
- expect(user0.tasks).to.lengthOf(1);
- expect(user0.tasks[0].title).to.equal(values.tasks[0].title, 'task title is correct');
- const user = await User.findOne({ where: { email: values.email } });
- const tasks = await user.getTasks();
- // Make sure tasks relationship is successful
- expect(tasks).to.be.an('array');
- expect(tasks).to.lengthOf(1);
- expect(tasks[0].title).to.equal(values.tasks[0].title, 'task title is correct');
- });
- it('should create nested associations with symmetric getters/setters on FK', async function () {
- // Dummy getter/setter to test they are symmetric
- function toCustomFormat(string) {
- return string && `FORMAT-${string}`;
- }
- function fromCustomFormat(string) {
- return string && string.slice(7);
- }
- const Parent = this.sequelize.define('Parent', {
- id: {
- type: DataTypes.STRING,
- primaryKey: true,
- get() {
- return fromCustomFormat(this.getDataValue('id'));
- },
- set(value) {
- this.setDataValue('id', toCustomFormat(value));
- },
- },
- });
- const Child = this.sequelize.define('Child', {
- id: {
- type: DataTypes.STRING,
- primaryKey: true,
- },
- parent: {
- type: DataTypes.STRING,
- get() {
- return fromCustomFormat(this.getDataValue('parent'));
- },
- set(value) {
- this.setDataValue('parent', toCustomFormat(value));
- },
- },
- });
- Child.belongsTo(Parent, {
- as: 'Parent',
- foreignKey: 'parent',
- targetKey: 'id',
- inverse: {
- type: 'hasMany',
- as: 'children',
- },
- });
- const values = {
- id: 'sJn369d8Em',
- children: [{ id: 'dgeQAQaW7A' }],
- };
- await this.sequelize.sync({ force: true });
- const father = await Parent.create(values, { include: { model: Child, as: 'children' } });
- // Make sure tasks are defined for created user
- expect(father.id).to.equal('sJn369d8Em');
- expect(father.get('id', { raw: true })).to.equal('FORMAT-sJn369d8Em');
- expect(father).to.have.property('children');
- expect(father.children).to.be.an('array');
- expect(father.children).to.lengthOf(1);
- expect(father.children[0].parent).to.equal('sJn369d8Em');
- expect(father.children[0].get('parent', { raw: true })).to.equal('FORMAT-sJn369d8Em');
- });
- });
- describe('sourceKey with where clause in include', () => {
- beforeEach(function () {
- this.User = this.sequelize.define(
- 'User',
- {
- username: DataTypes.STRING,
- email: { type: DataTypes.STRING, field: 'mail', allowNull: false },
- },
- { indexes: [{ fields: ['mail'], unique: true }] },
- );
- this.Task = this.sequelize.define('Task', {
- title: DataTypes.STRING,
- userEmail: DataTypes.STRING,
- taskStatus: DataTypes.STRING,
- });
- this.User.hasMany(this.Task, {
- foreignKey: 'userEmail',
- sourceKey: 'email',
- });
- return this.sequelize.sync({ force: true });
- });
- it('should use the specified sourceKey instead of the primary key', async function () {
- await this.User.create({ username: 'John', email: 'john@example.com' });
- await this.Task.bulkCreate([
- { title: 'Active Task', userEmail: 'john@example.com', taskStatus: 'Active' },
- { title: 'Inactive Task', userEmail: 'john@example.com', taskStatus: 'Inactive' },
- ]);
- const user = await this.User.findOne({
- include: [
- {
- model: this.Task,
- where: { taskStatus: 'Active' },
- },
- ],
- where: { username: 'John' },
- });
- expect(user).to.be.ok;
- expect(user.tasks.length).to.equal(1);
- expect(user.tasks[0].title).to.equal('Active Task');
- });
- });
- describe('Eager loading', () => {
- beforeEach(function () {
- this.Individual = this.sequelize.define('individual', {
- name: DataTypes.STRING,
- });
- this.Hat = this.sequelize.define('hat', {
- name: DataTypes.STRING,
- });
- this.Individual.hasMany(this.Hat, {
- as: {
- singular: 'personwearinghat',
- plural: 'personwearinghats',
- },
- });
- });
- it('should load with an alias', async function () {
- await this.sequelize.sync({ force: true });
- const [individual0, hat] = await Promise.all([
- this.Individual.create({ name: 'Foo Bar' }),
- this.Hat.create({ name: 'Baz' }),
- ]);
- await individual0.addPersonwearinghat(hat);
- const individual = await this.Individual.findOne({
- where: { name: 'Foo Bar' },
- include: [{ model: this.Hat, as: 'personwearinghats' }],
- });
- expect(individual.name).to.equal('Foo Bar');
- expect(individual.personwearinghats.length).to.equal(1);
- expect(individual.personwearinghats[0].name).to.equal('Baz');
- });
- it('should load all', async function () {
- await this.sequelize.sync({ force: true });
- const [individual0, hat] = await Promise.all([
- this.Individual.create({ name: 'Foo Bar' }),
- this.Hat.create({ name: 'Baz' }),
- ]);
- await individual0.addPersonwearinghat(hat);
- const individual = await this.Individual.findOne({
- where: { name: 'Foo Bar' },
- include: [{ all: true }],
- });
- expect(individual.name).to.equal('Foo Bar');
- expect(individual.personwearinghats.length).to.equal(1);
- expect(individual.personwearinghats[0].name).to.equal('Baz');
- });
- });
- });
|