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

Method set

lib/associations/has-many.js:327–392  ·  view source on GitHub ↗

* Set the associated models by passing an array of persisted instances or their primary keys. Everything that is 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[]|n

(sourceInstance, targetInstances, options)

Source from the content-addressed store, hash-verified

325 * @returns {Promise}
326 */
327 async set(sourceInstance, targetInstances, options) {
328 if (targetInstances === null) {
329 targetInstances = [];
330 } else {
331 targetInstances = this.toInstanceArray(targetInstances);
332 }
333
334 const oldAssociations = await this.get(sourceInstance, { ...options, scope: false, raw: true });
335 const promises = [];
336 const obsoleteAssociations = oldAssociations.filter(old =>
337 !targetInstances.find(obj =>
338 obj[this.target.primaryKeyAttribute] === old[this.target.primaryKeyAttribute]
339 )
340 );
341 const unassociatedObjects = targetInstances.filter(obj =>
342 !oldAssociations.find(old =>
343 obj[this.target.primaryKeyAttribute] === old[this.target.primaryKeyAttribute]
344 )
345 );
346 let updateWhere;
347 let update;
348
349 if (obsoleteAssociations.length > 0) {
350 update = {};
351 update[this.foreignKey] = null;
352
353 updateWhere = {
354 [this.target.primaryKeyAttribute]: obsoleteAssociations.map(associatedObject =>
355 associatedObject[this.target.primaryKeyAttribute]
356 )
357 };
358
359
360 promises.push(this.target.unscoped().update(
361 update,
362 {
363 ...options,
364 where: updateWhere
365 }
366 ));
367 }
368
369 if (unassociatedObjects.length > 0) {
370 updateWhere = {};
371
372 update = {};
373 update[this.foreignKey] = sourceInstance.get(this.sourceKey);
374
375 Object.assign(update, this.scope);
376 updateWhere[this.target.primaryKeyAttribute] = unassociatedObjects.map(unassociatedObject =>
377 unassociatedObject[this.target.primaryKeyAttribute]
378 );
379
380 promises.push(this.target.unscoped().update(
381 update,
382 {
383 ...options,
384 where: updateWhere

Callers

nothing calls this directly

Calls 6

getMethod · 0.95
toInstanceArrayMethod · 0.80
unscopedMethod · 0.80
allMethod · 0.80
getMethod · 0.65
updateMethod · 0.45

Tested by

no test coverage detected