diff --git a/lib/Associations/Extend.js b/lib/Associations/Extend.js index 5ec01cee..3df3c291 100644 --- a/lib/Associations/Extend.js +++ b/lib/Associations/Extend.js @@ -40,6 +40,42 @@ exports.prepare = function (db, Model, associations, association_properties, mod associations.push(association); + Model["findBy" + assocName] = function () { + var cb = null, conditions = null, options = {}; + + for (var i = 0; i < arguments.length; i++) { + switch (typeof arguments[i]) { + case "function": + cb = arguments[i]; + break; + case "object": + if (conditions === null) { + conditions = arguments[i]; + } else { + options = arguments[i]; + } + break; + } + } + + if (conditions === null) { + throw ErrorCodes.generateError(ErrorCodes.PARAM_MISMATCH, ".findBy(" + assocName + ") is missing a conditions object"); + } + + options.__merge = { + from : { table: association.model.table, field: Object.keys(association.field) }, + to : { table: Model.table, field: Model.id }, + where : [ association.model.table, conditions ], + table : Model.table + }; + options.extra = []; + + if (typeof cb == "function") { + return Model.find({}, options, cb); + } + return Model.find({}, options); + }; + return association.model; }; }; diff --git a/test/integration/association-extend.js b/test/integration/association-extend.js index 6f03f4fe..98b2a25e 100644 --- a/test/integration/association-extend.js +++ b/test/integration/association-extend.js @@ -212,4 +212,37 @@ describe("Model.extendsTo()", function() { }); }); }); + + describe("findBy()", function () { + before(setup()); + + it("should throw if no conditions passed", function (done) { + (function () { + Person.findByAddress(function () {}); + }).should.throw(); + + return done(); + }); + + it("should lookup in Model based on associated model properties", function (done) { + Person.findByAddress({ + number: 123 + }, function (err, people) { + should.equal(err, null); + should(Array.isArray(people)); + should(people.length == 1); + + return done(); + }); + }); + + it("should return a ChainFind if no callback passed", function (done) { + var ChainFind = Person.findByAddress({ + number: 123 + }); + ChainFind.run.should.be.a("function"); + + return done(); + }); + }); });