MCPcopy
hub / github.com/sequelize/sequelize / set

Method set

lib/associations/belongs-to-many.js:566–658  ·  view source on GitHub ↗

* 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 {Model} sourceInstance source instance to associate new instances with * @param {Model|Model[]|string[]|string|number[]|numbe

(sourceInstance, newAssociatedObjects, options)

Source from the content-addressed store, hash-verified

564 * @returns {Promise}
565 */
566 async set(sourceInstance, newAssociatedObjects, options) {
567 options = options || {};
568
569 const sourceKey = this.sourceKey;
570 const targetKey = this.targetKey;
571 const identifier = this.identifier;
572 const foreignIdentifier = this.foreignIdentifier;
573
574 if (newAssociatedObjects === null) {
575 newAssociatedObjects = [];
576 } else {
577 newAssociatedObjects = this.toInstanceArray(newAssociatedObjects);
578 }
579 const where = {
580 [identifier]: sourceInstance.get(sourceKey),
581 ...this.through.scope
582 };
583
584 const updateAssociations = currentRows => {
585 const obsoleteAssociations = [];
586 const promises = [];
587 const defaultAttributes = options.through || {};
588
589 const unassociatedObjects = newAssociatedObjects.filter(obj =>
590 !currentRows.some(currentRow => currentRow[foreignIdentifier] === obj.get(targetKey))
591 );
592
593 for (const currentRow of currentRows) {
594 const newObj = newAssociatedObjects.find(obj => currentRow[foreignIdentifier] === obj.get(targetKey));
595
596 if (!newObj) {
597 obsoleteAssociations.push(currentRow);
598 } else {
599 let throughAttributes = newObj[this.through.model.name];
600 // Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
601 if (throughAttributes instanceof this.through.model) {
602 throughAttributes = {};
603 }
604
605 const attributes = { ...defaultAttributes, ...throughAttributes };
606
607 if (Object.keys(attributes).length) {
608 promises.push(
609 this.through.model.update(attributes, Object.assign(options, {
610 where: {
611 [identifier]: sourceInstance.get(sourceKey),
612 [foreignIdentifier]: newObj.get(targetKey)
613 }
614 }
615 ))
616 );
617 }
618 }
619 }
620
621 if (obsoleteAssociations.length > 0) {
622 promises.push(
623 this.through.model.destroy({

Callers

nothing calls this directly

Calls 3

toInstanceArrayMethod · 0.80
findAllMethod · 0.80
getMethod · 0.65

Tested by

no test coverage detected