From a9cc1c38df4b8484ecb6f424917a83570712395e Mon Sep 17 00:00:00 2001 From: Clark Wang Date: Thu, 20 Nov 2014 19:27:04 +0800 Subject: [PATCH] Allow hasOne relation to have a scope option Signed-off-by: Clark Wang --- lib/relation-definition.js | 1 + test/relations.test.js | 48 +++++++++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 01409889..38f5552c 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -1448,6 +1448,7 @@ RelationDefinition.hasOne = function (modelFrom, modelTo, params) { keyTo: fk, modelTo: modelTo, properties: params.properties, + scope: params.scope, options: params.options, polymorphic: polymorphic }); diff --git a/test/relations.test.js b/test/relations.test.js index d7f63999..9bcbc390 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -1794,7 +1794,53 @@ describe('relations', function () { done(); }); }); - + + }); + + describe('hasOne with scope', function () { + + var Supplier, Account; + var supplierId, accountId; + + before(function () { + db = getSchema(); + Supplier = db.define('Supplier', {name: String}); + Account = db.define('Account', {accountNo: String, supplierName: String, block: Boolean}); + Supplier.hasOne(Account, { scope: { where: { block: false } }, properties: { name: 'supplierName' } }); + }); + + it('can be used to query data', function (done) { + db.automigrate(function () { + Supplier.create({name: 'Supplier 1'}, function (e, supplier) { + supplierId = supplier.id; + should.not.exist(e); + should.exist(supplier); + supplier.account.create({accountNo: 'a01'}, function (err, account) { + supplier.account(function (e, act) { + accountId = act.id; + should.not.exist(e); + should.exist(act); + act.should.be.an.instanceOf(Account); + supplier.account().id.should.equal(act.id); + act.supplierName.should.equal(supplier.name); + done(); + }); + }); + }); + }); + }); + + it('should find record that match scope', function (done) { + Account.updateAll({ block: true }, function (err) { + Supplier.findById(supplierId, function (err, supplier) { + supplier.account(function (err, account) { + should.not.exists(account); + done(); + }); + }); + }); + }); + }); describe('hasOne with non standard id', function () {