Created
October 12, 2016 00:17
-
-
Save BoLaMN/6590e8849d23f6373a177d5ccc42ef23 to your computer and use it in GitHub Desktop.
includeOneToOne
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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