Permalink
Browse files

Added ability to define name for opposite side of a one-to-many relat…

…ionship using hasOne
  • Loading branch information...
1 parent c6bdce1 commit 5f72f8132416621226114d24c09fc061e2271eeb Will Brady committed Jul 19, 2013
Showing with 54 additions and 0 deletions.
  1. +1 −0 README.md
  2. +2 −0 lib/model.js
  3. +51 −0 test/define.js
View
1 README.md
@@ -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__
View
2 lib/model.js
@@ -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);
}
View
51 test/define.js
@@ -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

0 comments on commit 5f72f81

Please sign in to comment.