From c99441247c81d790da8df4347aa65224a20f9797 Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Thu, 23 Mar 2017 05:06:36 +0800 Subject: [PATCH] Fix - `_targetClass` on scope function (#1280) Fix `_targetClass` on scope function when using hasManyThrough relation with customized relation names and foreignKey/keyThrough. This bug is cause by `_targetClass` uses the camel-case of `relationName`(e.g.: if `relationName` is `bbb`, `targetClass` would be `Bbb`), which is not exists. This will also suppress "not exposed" warnings when generating angular sdk, and generate end-points for this scope. --- lib/scope.js | 3 ++- test/relations.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/scope.js b/lib/scope.js index aeb72179..2cf71463 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -254,7 +254,8 @@ function defineScope(cls, targetClass, name, params, methods, options) { f._targetClass = targetModel.modelName; if (f._scope.collect) { - f._targetClass = i8n.camelize(f._scope.collect); + const rel = targetModel.relations[f._scope.collect]; + f._targetClass = rel && rel.modelTo && rel.modelTo.modelName || i8n.camelize(f._scope.collect); } f.getAsync = function(condOrRefresh, options, cb) { diff --git a/test/relations.test.js b/test/relations.test.js index 0c453d5a..ce16e31c 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -1364,6 +1364,30 @@ describe('relations', function() { }); }); + describe('hasMany through - customized relation name and foreign key', function() { + var Physician, Patient, Appointment; + + beforeEach(function(done) { + // db = getSchema(); + Physician = db.define('Physician', {name: String}); + Patient = db.define('Patient', {name: String}); + Appointment = db.define('Appointment', {date: {type: Date, defaultFn: 'now'}}); + + db.automigrate(['Physician', 'Patient', 'Appointment'], done); + }); + + it('should use real target class', function() { + Physician.hasMany(Patient, {through: Appointment, as: 'xxx', foreignKey: 'aaaId', keyThrough: 'bbbId'}); + Patient.hasMany(Physician, {through: Appointment, as: 'yyy', foreignKey: 'bbbId', keyThrough: 'aaaId'}); + Appointment.belongsTo(Physician, {as: 'aaa', foreignKey: 'aaaId'}); + Appointment.belongsTo(Patient, {as: 'bbb', foreignKey: 'bbbId'}); + var physician = new Physician({id: 1}); + physician.xxx.should.have.property('_targetClass', 'Patient'); + var patient = new Patient({id: 1}); + patient.yyy.should.have.property('_targetClass', 'Physician'); + }); + }); + describe('hasMany through bi-directional relations on the same model', function() { var User, Follow, Address;