Skip to content

Commit

Permalink
feat(lucid): add support for pluckFirst and pluckId
Browse files Browse the repository at this point in the history
added methods will return the value of the plucked field as the plain value instead of array or
object
  • Loading branch information
thetutlage committed Jun 7, 2016
1 parent bfd927d commit e3c17d8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Lucid/QueryBuilder/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,16 @@ methods.pair = function (target) {
}, {})
}
}

methods.pluckFirst = function (target) {
return function * (field) {
const firstRow = yield target.modelQueryBuilder.select(field).first()
return firstRow ? firstRow[field] : null
}
}

methods.pluckId = function (target) {
return function () {
return this.pluckFirst(target.HostModel.primaryKey)
}
}
23 changes: 23 additions & 0 deletions test/unit/lucid.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -873,6 +873,29 @@ describe('Lucid', function () {
expect(usersPair).deep.equal(manualPair)
})

it('should pluck the first matching column field and return as a plain value', function * () {
class User extends Model {
}
yield User.create({username: 'unique-user'})
const username = yield User.query().where('username', 'unique-user').pluckFirst('username')
expect(username).to.equal('unique-user')
})

it('should return null when pluckFirst has nothing found any rows', function * () {
class User extends Model {
}
const username = yield User.query().where('username', 'non-existing-user').pluckFirst('username')
expect(username).to.equal(null)
})

it('should pluck the first matching column id and return as a plain value', function * () {
class User extends Model {
}
const user = yield User.create({username: 'unique-user-for-id'})
const userId = yield User.query().where('username', 'unique-user-for-id').pluckId()
expect(userId).to.equal(user.id)
})

it('should throw ModelNotFoundException when unable to find a record using findOrFail method', function * () {
class User extends Model {
}
Expand Down

0 comments on commit e3c17d8

Please sign in to comment.