Skip to content

Commit

Permalink
Added setHasOne functionality (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
alechirsch authored and blah238 committed Sep 18, 2016
1 parent 2b5bfba commit b8364b2
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,30 @@ Manager.prototype.setBelongsToMany = function(model, key, models, relation, opti
});
};

Manager.prototype.setHasOne = function(model, key, value, relation, options) {
var Target = relation.relatedData.target;
var existing = Target.forge(model.related(key).attributes);
var target = Target.forge(value);
var fk = relation.relatedData.foreignKey;

if (value !== null) {
if (existing.get(fk)) {
existing.set(fk, null);
}
else{
target.set(fk, model.id);
return target.save();
}

return existing.save()
.then(function(){
target.set(fk, model.id);
return target.save();

});
}
};

Manager.prototype.setHasMany = function(model, key, models, relation, options) {
var existing = model.related(key);

Expand Down

0 comments on commit b8364b2

Please sign in to comment.