Skip to content

Commit

Permalink
Merge pull request #81 from wbrady/master
Browse files Browse the repository at this point in the history
Adds ability to define name for opposite side of a one-to-many relationship using hasOne
  • Loading branch information
joeferner committed Jul 19, 2013
2 parents c6bdce1 + 5f72f81 commit b449b19
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -461,6 +461,7 @@ __Arguments__
* foreignKey - The foreign key to use for the relationship
* name - the name of the property to expose.
* createHasMany - true/false to create the other side of the relationship.
* hasManyName - The name of the property on the other side of the relationship.

__Returns__

Expand Down
2 changes: 2 additions & 0 deletions lib/model.js
Expand Up @@ -332,6 +332,8 @@ exports.define = function (name, columnDefs, opts) {
if(!opts.hasOwnProperty('createHasMany') || opts.createHasMany) {
var associatedOpts = persistUtil.shallowCopy(opts);
delete associatedOpts.foreignKey;
associatedOpts.name = associatedOpts.hasManyName || associatedOpts.name;
delete associatedOpts.hasManyName;
associatedModel.hasMany(this, associatedOpts);
}

Expand Down
51 changes: 51 additions & 0 deletions test/define.js
Expand Up @@ -66,6 +66,57 @@ exports['Define'] = nodeunit.testCase({
test.done();
},

"hasOne with hasManyName": function(test) {
var Phone = persist.define("Phone", {
"number": type.STRING
});
var Person = persist.define("Person", {
"name": type.STRING
}).hasOne(Phone, { hasManyName: 'owners' });

var person = new Person();
assert.isNotUndefined(person.phone, "person.phone is undefined");

var phone = new Phone();
assert.isNotUndefined(phone.owners, "phone.owners is undefined");

test.done();
},

"hasOne with name and hasManyName": function(test) {
var Phone = persist.define("Phone", {
"number": type.STRING
});
var Person = persist.define("Person", {
"name": type.STRING
}).hasOne(Phone, { name: 'cellular', hasManyName: 'owners' });

var person = new Person();
assert.isNotUndefined(person.cellular, "person.cellular is undefined");

var phone = new Phone();
assert.isNotUndefined(phone.people, "phone.owners is undefined");

test.done();
},

"hasOne with name and no hasManyName": function(test) {
var Phone = persist.define("Phone", {
"number": type.STRING
});
var Person = persist.define("Person", {
"name": type.STRING
}).hasOne(Phone, { name: 'cellular' });

var person = new Person();
assert.isNotUndefined(person.cellular, "person.cellular is undefined");

var phone = new Phone();
assert.isNotUndefined(phone.people, "phone.people is undefined");

test.done();
},

"hasManyToMany": function(test) {
var Phone = persist.define("Phone", {
"number": type.STRING
Expand Down

0 comments on commit b449b19

Please sign in to comment.