From ec7f79e93523803f74e23bc6a136c315e7eb17cc Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Sat, 9 Nov 2013 22:16:32 -0800 Subject: [PATCH] Ensure the model is attached to DataSource for relations --- lib/datasource.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/datasource.js b/lib/datasource.js index a2749adf..3b95bf22 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -308,6 +308,10 @@ function isModelClass(cls) { DataSource.relationTypes = ['belongsTo', 'hasMany', 'hasAndBelongsToMany']; + +function isModelDataSourceAttached(model) { + return model && (!model.settings.unresolved) && (model.dataSource instanceof DataSource); +} /*! * Define relations for the model class from the relations object * @param modelClass @@ -317,7 +321,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { // Create a function for the closure in the loop var createListener = function (name, relation, targetModel, throughModel) { - if (targetModel && targetModel.settings.unresolved) { + if (!isModelDataSourceAttached(targetModel)) { targetModel.once('dataSourceAttached', function (model) { // Check if the through model doesn't exist or resolved if (!throughModel || !throughModel.settings.unresolved) { @@ -334,7 +338,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { } }); } - if (throughModel && throughModel.settings.unresolved) { + if (throughModel && !isModelDataSourceAttached(throughModel)) { // Set up a listener to the through model throughModel.once('dataSourceAttached', function (model) { if (!targetModel.settings.unresolved) { @@ -369,7 +373,7 @@ DataSource.prototype.defineRelations = function(modelClass, relations) { throughModel = this.define(r.through, {}, {unresolved: true}); } } - if (targetModel.settings.unresolved || (throughModel && throughModel.settings.unresolved)) { + if (!isModelDataSourceAttached(targetModel) || (throughModel && !isModelDataSourceAttached(throughModel))) { // Create a listener to defer the relation set up createListener(rn, r, targetModel, throughModel); } else {