Relations passed to belongsTo.add

This commit is contained in:
Anatoliy Chakkaev 2013-04-18 23:00:15 +04:00 committed by Raymond Feng
parent 504ae56acd
commit ee05ebcca6
1 changed files with 21 additions and 6 deletions

View File

@ -9,6 +9,14 @@ var defineScope = require('./scope.js').defineScope;
*/
var Model = require('./model.js');
Model.relationNameFor = function relationNameFor(foreignKey) {
for (var rel in this.relations) {
if (this.relations[rel].type === 'belongsTo' && this.relations[rel].keyFrom === foreignKey) {
return rel;
}
}
};
/**
* Declare hasMany relation
*
@ -36,7 +44,7 @@ Model.hasMany = function hasMany(anotherClass, params) {
i8n.camelize(i8n.pluralize(anotherClass.modelName), true);
var fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true);
this.relations[params['as']] = {
this.relations[methodName] = {
type: 'hasMany',
keyFrom: 'id',
keyTo: fk,
@ -57,12 +65,16 @@ Model.hasMany = function hasMany(anotherClass, params) {
done = data;
data = {};
}
if ('function' !== typeof done) {
done = function() {};
}
var self = this;
var id = this.id;
anotherClass.create(data, function(err, ac) {
if (err) return done(err, ac);
var d = {};
d[fk] = id;
d[fk2] = ac.id;
d[params.through.relationNameFor(fk)] = self;
d[params.through.relationNameFor(fk2)] = ac;
params.through.create(d, function(e) {
if (e) {
ac.destroy(function() {
@ -76,9 +88,12 @@ Model.hasMany = function hasMany(anotherClass, params) {
};
scopeMethods.add = function(acInst, done) {
var data = {};
data[fk] = this.id;
data[fk2] = acInst.id || acInst;
params.through.findOrCreate({where: data}, done);
var query = {};
query[fk] = this.id;
data[params.through.relationNameFor(fk)] = this;
query[fk2] = acInst.id || acInst;
data[params.through.relationNameFor(fk2)] = acInst;
params.through.findOrCreate({where: query}, data, done);
};
scopeMethods.remove = function(acInst, done) {
var self = this;