Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When setting hasMany set inverse relationship on matching belongsto #64

Open
wants to merge 1 commit into
base: fix/association-instances
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/viking/record/associations/collectionAssociation.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ export default class CollectionAssociation extends Association {
[this.foreignKey()]: this.owner.readAttribute(this.primaryKey())
})
}

const inverseAssociation = Object.values(record._associations).find(association => {
return association.reflection.macro == "belongsTo" && association.reflection.model == this.owner.constructor
})
if (inverseAssociation) {
inverseAssociation.setTarget(this.owner)
inverseAssociation.loaded = true
}

return record
});

Expand Down
25 changes: 23 additions & 2 deletions test/record/associations/hasManyTest.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
import * as assert from 'assert';
import 'mocha';
import VikingRecord from 'viking/record';
import { hasMany } from 'viking/record/associations';
import { hasMany, belongsTo } from 'viking/record/associations';
import {extendClass} from 'viking/support/class';

describe('Viking.Record::associations', () => {
describe('hasMany(Parent)', () => {
class Parent extends VikingRecord { }

function Parent () {
var NewTarget = Object.getPrototypeOf(this).constructor;
return Reflect.construct(VikingRecord, arguments, NewTarget);
}

class Model extends VikingRecord {
static associations = [hasMany(Parent)];
}

extendClass('Parent', VikingRecord, Parent, {
associations: [
belongsTo(Model)
]
})

it("load association", function(done) {
let model = new Model({id: 24});
Expand Down Expand Up @@ -45,6 +57,15 @@ describe('Viking.Record::associations', () => {
});
})

it("set inverse association", function () {
let model = new Model()
let parent = new Parent()

model.parents.add(parent)

assert.equal(model.cid, parent.model.cid)
})

it("add to association", function () {
let model = new Model()
let parent = new Parent()
Expand Down