diff --git a/lib/viking/record/associations/collectionAssociation.js b/lib/viking/record/associations/collectionAssociation.js index e38c3feb..90eddb4d 100644 --- a/lib/viking/record/associations/collectionAssociation.js +++ b/lib/viking/record/associations/collectionAssociation.js @@ -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 }); diff --git a/test/record/associations/hasManyTest.js b/test/record/associations/hasManyTest.js index 4f9394fc..195512b7 100644 --- a/test/record/associations/hasManyTest.js +++ b/test/record/associations/hasManyTest.js @@ -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}); @@ -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()