/
belongs-to-many.ts
1321 lines (1172 loc) · 43.9 KB
/
belongs-to-many.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import each from 'lodash/each';
import isEqual from 'lodash/isEqual';
import isPlainObject from 'lodash/isPlainObject';
import omit from 'lodash/omit';
import upperFirst from 'lodash/upperFirst';
import { AssociationError } from '../errors';
import type {
BulkCreateOptions,
CreateOptions,
CreationAttributes,
Filterable,
FindAttributeOptions,
FindOptions,
InstanceDestroyOptions,
InstanceUpdateOptions,
Transactionable,
ModelStatic,
Model,
WhereOptions,
AttributeNames,
Attributes,
Includeable,
ModelAttributes,
UpdateOptions,
ModelOptions,
} from '../model';
import { Op } from '../operators';
import type { Sequelize } from '../sequelize';
import { col, fn } from '../sequelize';
import { isModelStatic, isSameInitialModel } from '../utils/model-utils.js';
import { removeUndefined } from '../utils/object.js';
import { camelize } from '../utils/string.js';
import type { AllowArray } from '../utils/types.js';
import type {
AssociationScope,
ForeignKeyOptions,
MultiAssociationOptions,
MultiAssociationAccessors,
AssociationOptions,
NormalizedAssociationOptions,
Association,
} from './base';
import { MultiAssociation } from './base';
import type { BelongsTo } from './belongs-to';
import { HasMany } from './has-many';
import { HasOne } from './has-one';
import type { AssociationStatic } from './helpers';
import {
AssociationSecret,
defineAssociation,
mixinMethods, normalizeBaseAssociationOptions, normalizeForeignKeyOptions,
} from './helpers';
function addInclude(findOptions: FindOptions, include: Includeable) {
if (Array.isArray(findOptions.include)) {
findOptions.include.push(include);
} else if (!findOptions.include) {
findOptions.include = [include];
} else {
findOptions.include = [findOptions.include, include];
}
}
/**
* Many-to-many association with a join/through table.
* See {@link Model.belongsToMany}
*
* When the join table has additional attributes, these can be passed in the options object:
*
* ```js
* UserProject = sequelize.define('user_project', {
* role: DataTypes.STRING
* });
* User.belongsToMany(Project, { through: UserProject });
* Project.belongsToMany(User, { through: UserProject });
* // through is required!
*
* user.addProject(project, { through: { role: 'manager' }});
* ```
*
* All methods allow you to pass either a persisted instance, its primary key, or a mixture:
*
* ```js
* const project = await Project.create({ id: 11 });
* await user.addProjects([project, 12]);
* ```
*
* If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
*
* ```js
* p1.UserProjects = {
* started: true
* }
* user.setProjects([p1, p2], { through: { started: false }}) // The default value is false, but p1 overrides that.
* ```
*
* Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
* ```js
* const projects = await user.getProjects();
* const p1 = projects[0];
* p1.UserProjects.started // Is this project started yet?
* ```
*
* In the API reference below, add the name of the association to the method, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
*/
export class BelongsToMany<
SourceModel extends Model = Model,
TargetModel extends Model = Model,
ThroughModel extends Model = Model,
SourceKey extends AttributeNames<SourceModel> = any,
TargetKey extends AttributeNames<TargetModel> = any,
> extends MultiAssociation<
SourceModel,
TargetModel,
/* ForeignKey */ string,
TargetKey,
NormalizedBelongsToManyOptions<SourceKey, TargetKey, ThroughModel>
> {
readonly accessors: MultiAssociationAccessors;
get foreignKey(): string {
return this.fromSourceToThrough.foreignKey;
}
/**
* The name of the Foreign Key attribute, located on the through table, that points to the Target model.
*
* Not to be confused with @link {BelongsToMany.foreignKey}, which points to the Source model instead.
*/
get otherKey(): string {
return this.pairedWith.foreignKey;
}
/**
* @deprecated use {@link BelongsToMany#foreignKey}
*/
get identifier() {
return this.foreignKey;
}
/**
* The corresponding column name of {@link BelongsToMany#foreignKey}
*/
get identifierField(): string {
return this.fromThroughToSource.identifierField;
}
/**
* The corresponding column name of {@link BelongsToMany#otherKey}
*/
get foreignIdentifierField() {
return this.pairedWith.identifierField;
}
/**
* The name of the Attribute that the {@link foreignKey} fk (located on the Through Model) will reference on the Source model.
*/
get sourceKey(): SourceKey {
return this.fromThroughToSource.targetKey;
}
/**
* The name of the Column that the {@link foreignKey} fk (located on the Through Table) will reference on the Source model.
*/
get sourceKeyField(): string {
return this.fromThroughToSource.targetKeyField;
}
/**
* The name of the Attribute that the {@link otherKey} fk (located on the Through Model) will reference on the Target model.
*/
get targetKey(): TargetKey {
return this.pairedWith.sourceKey;
}
/**
* The name of the Column that the {@link otherKey} fk (located on the Through Table) will reference on the Target model.
*/
get targetKeyField(): string {
return this.pairedWith.sourceKeyField;
}
/**
* The corresponding association this entity is paired with.
*/
pairedWith: BelongsToMany<TargetModel, SourceModel, ThroughModel, TargetKey, SourceKey>;
// intermediary associations
// these create the actual associations on the model. Remove them would be a breaking change.
readonly fromSourceToThrough: HasMany<SourceModel, ThroughModel, SourceKey, any>;
readonly fromSourceToThroughOne: HasOne<SourceModel, ThroughModel, SourceKey, any>;
get fromThroughToSource(): BelongsTo<ThroughModel, SourceModel, any, SourceKey> {
return this.fromSourceToThrough.inverse;
}
get fromTargetToThrough(): HasMany<TargetModel, ThroughModel, TargetKey, any> {
return this.pairedWith.fromSourceToThrough;
}
get fromTargetToThroughOne(): HasOne<TargetModel, ThroughModel, TargetKey, any> {
return this.pairedWith.fromSourceToThroughOne;
}
get fromThroughToTarget(): BelongsTo<ThroughModel, TargetModel, any, TargetKey> {
return this.pairedWith.fromThroughToSource;
}
get through(): NormalizedThroughOptions<ThroughModel> {
return this.options.through;
}
get throughModel(): ModelStatic<ThroughModel> {
return this.through.model;
}
constructor(
secret: symbol,
source: ModelStatic<SourceModel>,
target: ModelStatic<TargetModel>,
options: NormalizedBelongsToManyOptions<SourceKey, TargetKey, ThroughModel>,
pair?: BelongsToMany<TargetModel, SourceModel, ThroughModel, TargetKey, SourceKey>,
parent?: Association<any>,
) {
super(secret, source, target, options, parent);
try {
this.pairedWith = pair ?? BelongsToMany.associate<TargetModel, SourceModel, ThroughModel, TargetKey, SourceKey>(
secret,
target,
source,
removeUndefined({
...options,
// note: we can't just use '...options.inverse' because we need to set to underfined if the option wasn't set
as: options.inverse?.as,
scope: options.inverse?.scope,
foreignKeyConstraints: options.inverse?.foreignKeyConstraints,
inverse: removeUndefined({
as: options.as,
scope: options.scope,
foreignKeyConstraints: options.foreignKeyConstraints,
}),
sourceKey: options.targetKey,
targetKey: options.sourceKey,
foreignKey: options.otherKey,
otherKey: options.foreignKey,
through: removeUndefined({
...options.through,
scope: undefined,
}),
}),
this,
this,
);
} catch (error) {
throw new AssociationError(`BelongsToMany associations automatically create the corresponding association on the target model,
but this association failed to create its paired association (BelongsToMany from ${target.name} to ${source.name}).
This may happen if you try to define the same BelongsToMany association on both sides of the association.
If that is the case, instead of doing this:
A.belongsToMany(B, { as: 'b', through: 'AB' });
B.belongsToMany(A, { as: 'a', through: 'AB' });
Do this:
A.belongsToMany(B, { as: 'b', through: 'AB', inverse: { as: 'a' } });
`, { cause: error });
}
// we'll need to access their foreign key (through .otherKey) in this constructor.
// this makes sure it's created
this.pairedWith.pairedWith = this;
const sourceKey = options?.sourceKey || (source.primaryKeyAttribute as TargetKey);
this.fromSourceToThrough = HasMany.associate(AssociationSecret, this.source, this.throughModel, removeUndefined({
as: `${this.name.plural}${upperFirst(this.pairedWith.name.plural)}`,
scope: this.through.scope,
foreignKey: {
...this.options.foreignKey,
allowNull: this.options.foreignKey.allowNull ?? false,
name: this.options.foreignKey.name || (
this.isSelfAssociation ? camelize(`${this.pairedWith.name.singular}_${sourceKey}`)
: camelize(`${this.source.options.name.singular}_${sourceKey}`)
),
},
sourceKey: this.options.sourceKey,
foreignKeyConstraints: this.options.foreignKeyConstraints,
hooks: this.options.hooks,
inverse: {
as: this.pairedWith.name.singular,
},
}), this);
this.fromSourceToThroughOne = HasOne.associate(AssociationSecret, this.source, this.throughModel, removeUndefined({
as: `${this.name.singular}${upperFirst(this.pairedWith.name.singular)}`,
scope: this.through.scope,
// foreignKey: this.options.foreignKey,
foreignKey: {
...this.options.foreignKey,
allowNull: this.options.foreignKey.allowNull ?? false,
name: this.options.foreignKey.name || (
this.isSelfAssociation ? camelize(`${this.pairedWith.name.singular}_${sourceKey}`)
: camelize(`${this.source.options.name.singular}_${sourceKey}`)
),
},
sourceKey: this.options.sourceKey,
foreignKeyConstraints: this.options.foreignKeyConstraints,
hooks: this.options.hooks,
inverse: {
as: this.pairedWith.name.singular,
},
}), this);
// Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
const plural = upperFirst(this.options.name.plural);
const singular = upperFirst(this.options.name.singular);
this.accessors = {
get: `get${plural}`,
set: `set${plural}`,
addMultiple: `add${plural}`,
add: `add${singular}`,
create: `create${singular}`,
remove: `remove${singular}`,
removeMultiple: `remove${plural}`,
hasSingle: `has${singular}`,
hasAll: `has${plural}`,
count: `count${plural}`,
};
this.#mixin(source.prototype);
// we are the 'parent' of the belongs-to-many pair
if (pair == null) {
this.#makeFkPairUnique();
}
}
#makeFkPairUnique() {
let hasPrimaryKey = false;
// remove any PKs previously defined by sequelize
// but ignore any keys that are part of this association (#5865)
each(this.through.model.rawAttributes, (attribute, attributeName) => {
if (!attribute.primaryKey) {
return;
}
if ([this.foreignKey, this.otherKey].includes(attributeName)) {
return;
}
if (attribute._autoGenerated) {
delete this.through.model.rawAttributes[attributeName];
return;
}
hasPrimaryKey = true;
});
if (!hasPrimaryKey) {
if (typeof this.through.unique === 'string') {
throw new TypeError(`BelongsToMany: Option "through.unique" can only be used if the through model's foreign keys are not also the primary keys.
Add your own primary key to the through model, on different attributes than the foreign keys, to be able to use this option.`);
}
this.throughModel.rawAttributes[this.foreignKey].primaryKey = true;
this.throughModel.rawAttributes[this.otherKey].primaryKey = true;
} else if (this.through.unique !== false) {
let uniqueKey;
if (typeof this.through.unique === 'string' && this.through.unique !== '') {
uniqueKey = this.through.unique;
} else {
const keys = [this.foreignKey, this.otherKey].sort();
uniqueKey = [this.through.model.tableName, ...keys, 'unique'].join('_');
}
this.throughModel.rawAttributes[this.foreignKey].unique = [{ name: uniqueKey }];
this.throughModel.rawAttributes[this.otherKey].unique = [{ name: uniqueKey }];
}
this.throughModel.refreshAttributes();
}
static associate<
S extends Model,
T extends Model,
ThroughModel extends Model,
SourceKey extends AttributeNames<S>,
TargetKey extends AttributeNames<T>,
>(
secret: symbol,
source: ModelStatic<S>,
target: ModelStatic<T>,
options: BelongsToManyOptions<SourceKey, TargetKey, ThroughModel>,
pair?: BelongsToMany<T, S, ThroughModel, TargetKey, SourceKey>,
parent?: Association<any>,
): BelongsToMany<S, T, ThroughModel, SourceKey, TargetKey> {
return defineAssociation<
BelongsToMany<S, T, ThroughModel, SourceKey, TargetKey>,
BelongsToManyOptions<SourceKey, TargetKey, ThroughModel>,
NormalizedBelongsToManyOptions<SourceKey, TargetKey, ThroughModel>
>(BelongsToMany, source, target, options, parent, normalizeOptions, newOptions => {
// self-associations must always set their 'as' parameter
if (isSameInitialModel(source, target)
// use 'options' because this will always be set in 'newOptions'
&& (!options.as || !options.inverse?.as || options.as === options.inverse.as)) {
throw new AssociationError('Both options "as" and "inverse.as" must be defined for belongsToMany self-associations, and their value must be different.');
}
return new BelongsToMany(secret, source, target, newOptions, pair, parent);
});
}
#mixin(modelPrototype: Model) {
mixinMethods(
this,
modelPrototype,
['get', 'count', 'hasSingle', 'hasAll', 'set', 'add', 'addMultiple', 'remove', 'removeMultiple', 'create'],
{
hasSingle: 'has',
hasAll: 'has',
addMultiple: 'add',
removeMultiple: 'remove',
},
);
}
/**
* Get everything currently associated with this, using an optional where clause.
*
* See {@link Model} for a full explanation of options
*
* @param instance instance
* @param options find options
*/
async get(instance: SourceModel, options?: BelongsToManyGetAssociationsMixinOptions<TargetModel>): Promise<TargetModel[]> {
const through = this.through;
const findOptions: FindOptions<Attributes<TargetModel>> = {
...options,
// TODO: current WhereOptions typings do not allow having 'WhereOptions' inside another 'WhereOptions'
// @ts-expect-error
where: {
[Op.and]: [
options?.where,
this.scope,
],
},
};
let throughWhere = {
[this.foreignKey]: instance.get(this.sourceKey),
};
if (through.scope) {
Object.assign(throughWhere, through.scope);
}
// If a user pass a where on the options through options, make an "and" with the current throughWhere
if (options?.through?.where) {
throughWhere = {
[Op.and]: [throughWhere, options.through.where],
};
}
addInclude(findOptions, removeUndefined({
association: this.fromTargetToThroughOne,
attributes: options?.joinTableAttributes,
required: true,
paranoid: options?.through?.paranoid ?? true,
where: throughWhere,
}));
let model = this.target;
if (options?.scope != null) {
if (!options.scope) {
model = model.unscoped();
} else if (options.scope !== true) { // 'true' means default scope. Which is the same as not doing anything.
model = model.scope(options.scope);
}
}
if (options?.schema) {
model = model.schema(options.schema, options.schemaDelimiter);
}
return model.findAll(findOptions);
}
/**
* Count everything currently associated with this, using an optional where clause.
*
* @param instance instance
* @param options find options
*/
async count(instance: SourceModel, options?: BelongsToManyCountAssociationsMixinOptions<TargetModel>): Promise<number> {
const getOptions: BelongsToManyGetAssociationsMixinOptions<TargetModel> = {
...options,
attributes: [
[fn('COUNT', col([this.target.name, this.targetKeyField].join('.'))), 'count'],
],
joinTableAttributes: [],
raw: true,
plain: true,
};
const result = await this.get(instance, getOptions);
// @ts-expect-error -- this.get() isn't designed to expect returning a raw output.
return Number.parseInt(result.count, 10);
}
/**
* Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
*
* @param sourceInstance source instance to check for an association with
* @param targetInstancesOrPks Can be an array of instances or their primary keys
* @param options Options passed to getAssociations
*/
async has(
sourceInstance: SourceModel,
targetInstancesOrPks: AllowArray<TargetModel | Exclude<TargetModel[TargetKey], any[]>>,
options?: BelongsToManyHasAssociationMixinOptions<TargetModel>,
): Promise<boolean> {
if (!Array.isArray(targetInstancesOrPks)) {
targetInstancesOrPks = [targetInstancesOrPks];
}
const targetPrimaryKeys: Array<TargetModel[TargetKey]> = targetInstancesOrPks.map(instance => {
if (instance instanceof this.target) {
return (instance as TargetModel).get(this.targetKey);
}
return instance as TargetModel[TargetKey];
});
const associatedObjects: TargetModel[] = await this.get(sourceInstance, {
...options,
raw: true,
scope: false,
attributes: [this.targetKey],
joinTableAttributes: [],
// TODO: current WhereOptions typings do not allow having 'WhereOptions' inside another 'WhereOptions'
// @ts-expect-error
where: {
[Op.and]: [
{ [this.targetKey]: { [Op.in]: targetPrimaryKeys } },
options?.where,
],
},
});
return targetPrimaryKeys.every(pk => {
return associatedObjects.some(instance => {
// instance[x] instead of instance.get() because the query output is 'raw'
// isEqual is used here because the PK can be a non-primitive value, such as a Buffer
return isEqual(instance[this.targetKey], pk);
});
});
}
/**
* Set the associated models by passing an array of instances or their primary keys.
* Everything that it not in the passed array will be un-associated.
*
* @param sourceInstance source instance to associate new instances with
* @param newInstancesOrPrimaryKeys A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param options Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
*/
async set(
sourceInstance: SourceModel,
newInstancesOrPrimaryKeys: AllowArray<TargetModel | Exclude<TargetModel[TargetKey], any[]>>,
options: BelongsToManySetAssociationsMixinOptions<TargetModel> = {},
): Promise<void> {
const sourceKey = this.sourceKey;
const targetKey = this.targetKey;
const foreignKey = this.foreignKey;
const otherKey = this.otherKey;
const newInstances = newInstancesOrPrimaryKeys === null ? [] : this.toInstanceArray(newInstancesOrPrimaryKeys);
const where = {
[foreignKey]: sourceInstance.get(sourceKey),
...this.through.scope,
};
const currentThroughRows: ThroughModel[] = await this.through.model.findAll({
...options,
where,
raw: true,
// force this option to be false, in case the user enabled
rejectOnEmpty: false,
include: this.scope ? [{
association: this.fromThroughToTarget,
where: this.scope,
required: true,
}] : [],
});
const obsoleteTargets: Array<TargetModel | Exclude<TargetModel[TargetKey], any[]>> = [];
// find all obsolete targets
for (const currentRow of currentThroughRows) {
const newTarget = newInstances.find(obj => {
// @ts-expect-error -- the findAll call is raw, no model here
return currentRow[otherKey] === obj.get(targetKey);
});
if (!newTarget) {
// @ts-expect-error -- the findAll call is raw, no model here
obsoleteTargets.push(currentRow[this.otherKey]);
}
}
const promises: Array<Promise<any>> = [];
if (obsoleteTargets.length > 0) {
promises.push(this.remove(sourceInstance, obsoleteTargets, options));
}
if (newInstances.length > 0) {
promises.push(this.#updateAssociations(sourceInstance, currentThroughRows, newInstances, options));
}
await Promise.all(promises);
}
/**
* Associate one or several rows with source instance. It will not un-associate any already associated instance
* that may be missing from `newInstances`.
*
* @param sourceInstance source instance to associate new instances with
* @param newInstancesOrPrimaryKeys A single instance or primary key, or a mixed array of persisted instances or primary keys
* @param options Options passed to `through.findAll`, `bulkCreate` and `update`
*/
async add(
sourceInstance: SourceModel,
newInstancesOrPrimaryKeys: AllowArray<TargetModel | Exclude<TargetModel[TargetKey], any[]>>,
options?: BelongsToManyAddAssociationsMixinOptions<TargetModel>,
): Promise<void> {
// If newInstances is null or undefined, no-op
if (!newInstancesOrPrimaryKeys) {
return;
}
const newInstances = this.toInstanceArray(newInstancesOrPrimaryKeys);
let currentRows: any[] = [];
if (this.through?.unique ?? true) {
currentRows = await this.through.model.findAll({
...options,
raw: true,
where: {
[this.foreignKey]: sourceInstance.get(this.sourceKey),
[this.otherKey]: newInstances.map(newInstance => newInstance.get(this.targetKey)),
...this.through.scope,
},
// force this option to be false, in case the user enabled
rejectOnEmpty: false,
});
}
await this.#updateAssociations(sourceInstance, currentRows, newInstances, options);
}
/**
* Adds new target instances that were not already present in the through table.
* Updates the through table row of the instances that already were present.
*
* @param sourceInstance
* @param currentThroughRows
* @param newTargets
* @param options
* @private
*/
async #updateAssociations(
sourceInstance: SourceModel,
currentThroughRows: ThroughModel[],
newTargets: TargetModel[],
options?:
& { through?: JoinTableAttributes }
& BulkCreateOptions<Attributes<ThroughModel>>
& Omit<UpdateOptions<Attributes<ThroughModel>>, 'where'>,
) {
const sourceKey = this.sourceKey;
const targetKey = this.targetKey;
const foreignKey = this.foreignKey;
const otherKey = this.otherKey;
const defaultAttributes = options?.through || {};
const promises: Array<Promise<any>> = [];
const unassociatedTargets: TargetModel[] = [];
// the 'through' table of these targets has changed
const changedTargets: TargetModel[] = [];
for (const newInstance of newTargets) {
const existingThroughRow = currentThroughRows.find(throughRow => {
// @ts-expect-error -- throughRow[] instead of .get because throughRows are loaded using 'raw'
return throughRow[otherKey] === newInstance.get(targetKey);
});
if (!existingThroughRow) {
unassociatedTargets.push(newInstance);
continue;
}
// @ts-expect-error -- gets the content of the "through" table for this association that is set on the model
const throughAttributes = newInstance[this.through.model.name];
const attributes = { ...defaultAttributes, ...throughAttributes };
if (Object.keys(attributes).some(attribute => {
// @ts-expect-error existingThroughRow is raw
return attributes[attribute] !== existingThroughRow[attribute];
})) {
changedTargets.push(newInstance);
}
}
if (unassociatedTargets.length > 0) {
const bulk = unassociatedTargets.map(unassociatedTarget => {
// @ts-expect-error -- gets the content of the "through" table for this association that is set on the model
const throughAttributes = unassociatedTarget[this.through.model.name];
const attributes = { ...defaultAttributes, ...throughAttributes };
attributes[foreignKey] = sourceInstance.get(sourceKey);
attributes[otherKey] = unassociatedTarget.get(targetKey);
Object.assign(attributes, this.through.scope);
return attributes;
});
promises.push(this.through.model.bulkCreate(bulk, { validate: true, ...options }));
}
for (const changedTarget of changedTargets) {
// @ts-expect-error -- gets the content of the "through" table for this association that is set on the model
let throughAttributes = changedTarget[this.through.model.name];
const attributes = { ...defaultAttributes, ...throughAttributes };
// Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
if (throughAttributes instanceof this.through.model) {
throughAttributes = {};
}
promises.push(this.through.model.update(attributes, {
...options,
where: {
[foreignKey]: sourceInstance.get(sourceKey),
[otherKey]: changedTarget.get(targetKey),
},
}));
}
await Promise.all(promises);
}
/**
* Un-associate one or more instance(s).
*
* @param sourceInstance instance to un associate instances with
* @param targetInstanceOrPks Can be an Instance or its primary key, or a mixed array of instances and primary keys
* @param options Options passed to `through.destroy`
*/
async remove(
sourceInstance: SourceModel,
targetInstanceOrPks: AllowArray<TargetModel | Exclude<TargetModel[TargetKey], any[]>>,
options?: BelongsToManyRemoveAssociationMixinOptions,
): Promise<void> {
const targetInstance = this.toInstanceArray(targetInstanceOrPks);
const where = {
[this.foreignKey]: sourceInstance.get(this.sourceKey),
[this.otherKey]: targetInstance.map(newInstance => newInstance.get(this.targetKey)),
...this.through.scope,
};
await this.through.model.destroy({ ...options, where });
}
/**
* Create a new instance of the associated model and associate it with this.
*
* @param sourceInstance source instance
* @param values values for target model
* @param options Options passed to create and add
*/
async create(
sourceInstance: SourceModel,
// @ts-expect-error -- {} is not always assignable to 'values', but Target.create will enforce this, not us.
values: CreationAttributes<TargetModel> = {},
options:
| BelongsToManyCreateAssociationMixinOptions<TargetModel>
| BelongsToManyCreateAssociationMixinOptions<TargetModel>['fields'] = {},
): Promise<TargetModel> {
if (Array.isArray(options)) {
options = {
fields: options,
};
}
if (this.scope) {
Object.assign(values, this.scope);
if (options.fields) {
options.fields = [...options.fields, ...Object.keys(this.scope)];
}
}
// Create the related model instance
const newAssociatedObject = await this.target.create(values, options);
await this.add(sourceInstance, newAssociatedObject, omit(options, ['fields']));
return newAssociatedObject;
}
}
// workaround https://github.com/evanw/esbuild/issues/1260
Object.defineProperty(BelongsToMany, 'name', {
value: 'BelongsToMany',
});
export function isThroughOptions<M extends Model>(val: any): val is ThroughOptions<M> {
return isPlainObject(val) && 'model' in val;
}
function normalizeThroughOptions<M extends Model>(
source: ModelStatic<any>,
target: ModelStatic<any>,
through: ThroughOptions<M>,
sequelize: Sequelize,
): NormalizedThroughOptions<M> {
const timestamps = through.timestamps ?? sequelize.options.define?.timestamps;
let model: ModelStatic<M>;
if (!through || (typeof through.model !== 'string' && !isModelStatic<M>(through.model))) {
throw new AssociationError(`${source.name}.belongsToMany(${target.name}) requires a through model, set the "through", or "through.model" options to either a string or a model`);
}
if (isModelStatic<M>(through.model)) {
model = through.model;
} else if (sequelize.isDefined(through.model)) {
model = sequelize.model<M>(through.model);
} else {
model = sequelize.define(through.model, {} as ModelAttributes<M>, removeUndefined({
tableName: through.model,
indexes: [], // we don't want indexes here (as referenced in #2416)
paranoid: through.paranoid || false, // Default to non-paranoid join (referenced in #11991)
validate: {}, // Don't propagate model-level validations
timestamps: through.timestamps,
// @ts-expect-error -- TODO: make 'schema' a public property on Model once the method has been removed (sequelize 8)
schema: source._schema,
// @ts-expect-error
schemaDelimiter: source._schemaDelimiter,
}));
}
return removeUndefined({
...through,
timestamps,
model,
});
}
function normalizeOptions<SourceKey extends string, TargetKey extends string, ThroughModel extends Model>(
type: AssociationStatic<any>,
options: BelongsToManyOptions<SourceKey, TargetKey, ThroughModel>,
source: ModelStatic<Model>,
target: ModelStatic<Model>,
): NormalizedBelongsToManyOptions<SourceKey, TargetKey, ThroughModel> {
if ('timestamps' in options) {
throw new TypeError('The "timestamps" option in belongsToMany has been renamed to through.timestamps');
}
if ('uniqueKey' in options) {
throw new TypeError('The "uniqueKey" option in belongsToMany has been renamed to through.unique');
}
const sequelize = target.sequelize;
return normalizeBaseAssociationOptions(type, {
...options,
otherKey: normalizeForeignKeyOptions(options.otherKey),
through: removeUndefined(isThroughOptions(options.through)
? normalizeThroughOptions(source, target, options.through, sequelize)
: normalizeThroughOptions(source, target, { model: options.through }, sequelize)),
}, source, target);
}
/**
* Used for the through table in n:m associations.
*
* Used in {@link BelongsToManyOptions.through}
*/
export interface ThroughOptions<ThroughModel extends Model> {
/**
* The model used to join both sides of the N:M association.
* Can be a string if you want the model to be generated by sequelize.
*/
model: ModelStatic<ThroughModel> | string;
/**
* See {@link ModelOptions.timestamps}
*/
timestamps?: ModelOptions['timestamps'];
/**
* See {@link ModelOptions.paranoid}
*/
paranoid?: ModelOptions['paranoid'];
/**
* A key/value set that will be used for association create and find defaults on the through model.
* (Remember to add the attributes to the through model)
*/
scope?: AssociationScope;
/**
* If true a unique constraint will be added on the foreign key pair.
* If set to a string, the generated unique key will use the string as its name.
* If set to false, no unique constraint will be added.
* Useful if you want to turn this off and create your own unique constraint when using scopes.
*
* This option only works if the model already has a Primary Key,
* as the unique constraint will not be added if the foreign keys are already part of the composite primary key.
*
* @default true
*/
unique?: boolean | string;
}
/**
* Attributes for the join table
*/
export interface JoinTableAttributes {
[attribute: string]: unknown;
}
type NormalizedBelongsToManyOptions<
SourceKey extends string,
TargetKey extends string,
ThroughModel extends Model,
> =
& Omit<BelongsToManyOptions<SourceKey, TargetKey, ThroughModel>, 'through' | 'as' | 'hooks' | 'foreignKey'>
& { through: NormalizedThroughOptions<ThroughModel> }
& Pick<NormalizedAssociationOptions<string>, 'as' | 'name' | 'hooks' | 'foreignKey'>;
type NormalizedThroughOptions<ThroughModel extends Model> = Omit<ThroughOptions<ThroughModel>, 'model'> & {
model: ModelStatic<ThroughModel>,
};
/**
* Options provided when associating models with belongsToMany relationship.
*
* Used by {@link Model.belongsToMany}.
*/
export interface BelongsToManyOptions<
SourceKey extends string = string,
TargetKey extends string = string,
ThroughModel extends Model = Model,
> extends MultiAssociationOptions<AttributeNames<ThroughModel>> {
/**
* Configures this association on the target model.
*/
inverse?: {
as?: AssociationOptions<string>['as'],
scope?: MultiAssociationOptions<string>['scope'],
foreignKeyConstraints?: AssociationOptions<string>['foreignKeyConstraints'],
};
// this is also present in AssociationOptions, but they have different JSDoc, keep both!
/**
* Should "ON UPDATE", "ON DELETE" and "REFERENCES" constraints be enabled on the foreign key?
*
* This only affects the foreign key that points to the source model.
* to control the one that points to the target model, set {@link BelongsToManyOptions.inverse.foreignKeyConstraints}.
*/
foreignKeyConstraints?: boolean;
/**
* The name of the table that is used to join source and target in n:m associations. Can also be a
* sequelize model if you want to define the junction table yourself and add extra attributes to it.
*/
through: ModelStatic<ThroughModel> | string | ThroughOptions<ThroughModel>;
/**
* The name of the foreign key in the join table (representing the target model) or an object representing
* the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you
* can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of
* target
*/
otherKey?: AttributeNames<ThroughModel> | ForeignKeyOptions<AttributeNames<ThroughModel>>;
/**
* The name of the field to use as the key for the association in the source table. Defaults to the primary