diff --git a/src/LucidMongo/Relations/BelongsToMany.js b/src/LucidMongo/Relations/BelongsToMany.js index 31b8083..4ecfdfa 100644 --- a/src/LucidMongo/Relations/BelongsToMany.js +++ b/src/LucidMongo/Relations/BelongsToMany.js @@ -18,6 +18,7 @@ const _ = require('lodash') const GE = require('@adonisjs/generic-exceptions') +const { ioc } = require('../../../lib/iocResolver') const BaseRelation = require('./BaseRelation') const util = require('../../../lib/util') @@ -313,7 +314,7 @@ class BelongsToMany extends BaseRelation { * @chainable */ pivotModel (pivotModel) { - this._PivotModel = pivotModel + this._PivotModel = typeof (pivotModel) === 'string' ? ioc.use(pivotModel) : pivotModel return this } diff --git a/test/unit/lucid-belongs-to-many.spec.js b/test/unit/lucid-belongs-to-many.spec.js index e541126..d724d56 100644 --- a/test/unit/lucid-belongs-to-many.spec.js +++ b/test/unit/lucid-belongs-to-many.spec.js @@ -1364,4 +1364,28 @@ test.group('Relations | Belongs To Many', (group) => { assert.equal(String(pivotValues[0].user_id), String(user.primaryKeyValue)) assert.equal(String(pivotValues[0].post_id), String(postId2)) }) + + test('define pivot model via ioc container string', (assert) => { + class Post extends Model { + } + + ioc.fake('App/Models/PostUser', () => { + class PostUser extends Model { + } + return PostUser + }) + + class User extends Model { + posts () { + return this.belongsToMany(Post).pivotModel('App/Models/PostUser') + } + } + + User._bootIfNotBooted() + Post._bootIfNotBooted() + + const user = new User() + const userPosts = user.posts() + assert.equal(userPosts.$pivotCollection, 'post_users') + }) }) diff --git a/test/unit/lucid-refer-many.spec.js b/test/unit/lucid-refer-many.spec.js index 20e52ca..55998be 100644 --- a/test/unit/lucid-refer-many.spec.js +++ b/test/unit/lucid-refer-many.spec.js @@ -700,7 +700,6 @@ test.group('Relations | Refer Many', (group) => { await user2.posts().attach(post2._id) const users = await ioc.use('Database').collection('users').find() - console.log(users) assert.lengthOf(users, 2) assert.lengthOf(users[0].post_ids, 1) assert.lengthOf(users[1].post_ids, 2)