Permalink
Browse files

auto add foreignkey for self associated has one and belongs to associ…

…ations
  • Loading branch information...
1 parent b669ea3 commit 5f373ddd1be837153b1f94b3bb321c0a3038b3d1 @sdepold committed May 9, 2011
View
4 lib/sequelize/associations/belongs-to.js
@@ -6,6 +6,10 @@ var BelongsTo = module.exports = function(srcModel, targetModel, options) {
this.target = targetModel
this.options = options
this.isSelfAssociation = (this.source.tableName == this.target.tableName)
+
+ if(this.isSelfAssociation && !this.options.foreignKey && !!this.options.as)
+ this.options.foreignKey = Utils._.underscoredIf(Utils.singularize(this.options.as) + "Id", this.source.options.underscored)
+
this.associationAccessor = this.isSelfAssociation
? Utils.combineTableNames(this.target.tableName, this.options.as || this.target.tableName)
: this.target.tableName
View
3 lib/sequelize/associations/has-one.js
@@ -7,6 +7,9 @@ var HasOne = module.exports = function(srcModel, targetModel, options) {
this.options = options
this.isSelfAssociation = (this.source.tableName == this.target.tableName)
+ if(this.isSelfAssociation && !this.options.foreignKey && !!this.options.as)
+ this.options.foreignKey = Utils._.underscoredIf(Utils.singularize(this.options.as) + "Id", this.options.underscored)
+
this.associationAccessor = this.isSelfAssociation
? Utils.combineTableNames(this.target.tableName, this.options.as || this.target.tableName)
: this.target.tableName
View
7 test/Model/belongs-to.js
@@ -117,5 +117,12 @@ module.exports = {
assert.isDefined(p.setMother)
exit(function(){})
})
+ },
+ 'it should automatically set the foreignKey if it is a self association': function() {
+ var num = config.rand()
+ var Person = sequelize.define('Person' + num, { name: Sequelize.STRING })
+
+ Person.belongsTo(Person, {as: 'Mother'})
+ assert.eql(Person.associations["MotherPerson"+num+"s"].options.foreignKey, 'MotherId')
}
}
View
7 test/Model/has-one.js
@@ -111,5 +111,12 @@ module.exports = {
assert.isDefined(p.setMother)
exit(function(){})
})
+ },
+ 'it should automatically set the foreignKey if it is a self association': function() {
+ var num = config.rand()
+ var Person = sequelize.define('Person' + num, { name: Sequelize.STRING })
+
+ Person.hasOne(Person, {as: 'Mother'})
+ assert.eql(Person.associations["MotherPerson"+num+"s"].options.foreignKey, 'MotherId')
}
}

0 comments on commit 5f373dd

Please sign in to comment.