Skip to content

Commit

Permalink
fix(belongsToMany): pivotModel should allow class and ioc container s…
Browse files Browse the repository at this point in the history
…tring

closes #254
  • Loading branch information
thetutlage committed Dec 14, 2017
1 parent 892208b commit 80fc99c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Lucid/Relations/BelongsToMany.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -422,7 +423,7 @@ class BelongsToMany extends BaseRelation {
* @chainable
*/
pivotModel (pivotModel) {
this._PivotModel = pivotModel
this._PivotModel = typeof (pivotModel) === 'string' ? ioc.use(pivotModel) : pivotModel
return this
}

Expand Down
24 changes: 24 additions & 0 deletions test/unit/lucid-belongs-to-many.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2004,4 +2004,28 @@ test.group('Relations | Belongs To Many', (group) => {
assert.equal(pivotValues[0].user_id, 1)
assert.equal(pivotValues[0].post_id, 2)
})

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.$pivotTable, 'post_users')
})
})

0 comments on commit 80fc99c

Please sign in to comment.