Skip to content

Instantly share code, notes, and snippets.

@BoLaMN
Created October 12, 2016 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoLaMN/6590e8849d23f6373a177d5ccc42ef23 to your computer and use it in GitHub Desktop.
Save BoLaMN/6590e8849d23f6373a177d5ccc42ef23 to your computer and use it in GitHub Desktop.
includeOneToOne
function includeOneToOne(callback) {
var targetIds = [];
var objTargetIdMap = {};
var lookupKey = (relation.type === 'belongsTo') ? relation.keyFrom : relation.keyTo;
for (var i = 0; i < objs.length; i++) {
var obj = objs[i];
if (relation.type === 'belongsTo') {
if (obj[lookupKey] === null ||
obj[lookupKey] === undefined) {
defineCachedRelations(obj);
obj.__cachedRelations[relationName] = null;
continue;
}
}
var targetId = obj[lookupKey];
if (targetId) {
targetIds.push(targetId);
var targetIdStr = targetId.toString();
objTargetIdMap[targetIdStr] = objTargetIdMap[targetIdStr] || [];
objTargetIdMap[targetIdStr].push(obj);
}
defineCachedRelations(obj);
obj.__cachedRelations[relationName] = null;
}
filter.where[lookupKey] = {
inq: uniq(targetIds)
};
relation.applyScope(null, filter);
findWithForeignKeysByPage(relation.modelTo, filter,
lookupKey, 0, options, targetFetchHandler);
/**
* Process fetched related objects
* @param err
* @param {Array<Model>} targets
* @returns {*}
*/
function targetFetchHandler(err, targets) {
if (err) {
return callback(err);
}
var tasks = [];
//simultaneously process subIncludes
if (subInclude && targets) {
tasks.push(function subIncludesTask(next) {
relation.modelTo.include(targets, subInclude, options, next);
});
}
//process each target object
tasks.push(targetLinkingTask);
function targetLinkingTask(next) {
async.each(targets, linkOneToMany, next);
function linkOneToMany(target, next) {
var targetId = obj[lookupKey];
var objList = objTargetIdMap[targetId.toString()];
async.each(objList, function(obj, next) {
if (!obj) return next();
obj.__cachedRelations[relationName] = target;
processTargetObj(obj, next);
}, next);
}
}
execTasksWithInterLeave(tasks, callback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment