Skip to content

Commit

Permalink
fix(belongsToMany): pivotModel allow class and ioc container string
Browse files Browse the repository at this point in the history
  • Loading branch information
Duy Luong committed Dec 24, 2017
1 parent 851071b commit d76e839
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/LucidMongo/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 @@ -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
}

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 @@ -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')
})
})
1 change: 0 additions & 1 deletion test/unit/lucid-refer-many.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit d76e839

Please sign in to comment.