Skip to content

Commit

Permalink
fix relationship add bug
Browse files Browse the repository at this point in the history
  • Loading branch information
MyMediaMagnet committed Mar 28, 2018
1 parent 7ae532c commit e99fd0c
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
12 changes: 10 additions & 2 deletions dist/models/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ var Model = function (_Query) {
throw new TypeError("Cannot construct Model instances directly");
}

// Save any relationships so we don't always create a new relationship class when called
var _this = _possibleConstructorReturn(this, (Model.__proto__ || Object.getPrototypeOf(Model)).call(this));

_this.relations = [];

if (data) {
_this.set(data);
}
Expand Down Expand Up @@ -116,9 +119,14 @@ var Model = function (_Query) {
}, {
key: 'hasMany',
value: function hasMany(instance) {
var items = this['_' + instance.route()];
var key = '_' + instance.route();
var items = this[key];

if (!this.relations[key]) {
this.relations[key] = new _Relationship2.default(instance, items, this);
}

return new _Relationship2.default(instance, items, this);
return this.relations[key];
}

/**
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "model-collection-js",
"version": "0.1.12",
"version": "0.1.13",
"description": "Javascript enabled Models and Collections to reflect Laravel workflow",
"main": "dist/index.js",
"scripts": {
Expand Down
12 changes: 10 additions & 2 deletions src/models/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ class Model extends Query{

super()

// Save any relationships so we don't always create a new relationship class when called
this.relations = []

if(data) {
this.set(data)
}
Expand Down Expand Up @@ -87,9 +90,14 @@ class Model extends Query{
* @returns Relationship
*/
hasMany(instance) {
let items = this['_' + instance.route()]
let key = '_' + instance.route()
let items = this[key]

if(!this.relations[key]) {
this.relations[key] = new Relationship(instance, items, this)
}

return new Relationship(instance, items, this)
return this.relations[key]
}

/**
Expand Down
5 changes: 5 additions & 0 deletions test/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ describe('#Model', function() {
expect(post.comments().first().user().name).to.equal('Jack')
expect(post.comments().last().user().name).to.equal('Jones')
expect(post.comments().get()).to.instanceof(Array)

post.comments().add({id:1002, body: 'some new comment', user:{id: 102, name: 'James', email: 'james@tester.com'}})

expect(post.comments().count()).to.equal(3)
expect(post.comments().last().id).to.equal(1002)
});


Expand Down

0 comments on commit e99fd0c

Please sign in to comment.