Skip to content

Commit

Permalink
feat(model): implement static first and last
Browse files Browse the repository at this point in the history
first and last returns model instance for the first and the last row
  • Loading branch information
thetutlage committed Nov 27, 2016
1 parent 1d00425 commit 2a74d6e
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Lucid/Model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,24 @@ class Model {
return yield this.query().pair(lhs, rhs)
}

/**
* Return the first row from the database
*
* @returns {Object}
*/
static first () {
return this.query().first()
}

/**
* Return the last row from the database
*
* @returns {Object}
*/
static last () {
return this.query().last()
}

/**
* truncate model database table
*
Expand Down
16 changes: 16 additions & 0 deletions src/Lucid/QueryBuilder/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,22 @@ methods.first = function (target) {
}
}

/**
* Returns the last record from the data collection
*
* @param {Object} target
* @return {Object}
*
* @public
*/
methods.last = function (target) {
return function * () {
target.modelQueryBuilder.orderBy(target.HostModel.primaryKey, 'desc').limit(1)
const results = yield this.fetch()
return results.first() || null
}
}

/**
* returns the first record from data collection
* or fails by throwing an exception
Expand Down
28 changes: 28 additions & 0 deletions test/unit/lucid.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2143,5 +2143,33 @@ describe('Lucid', function () {
User.bootIfNotBooted()
expect(User.findByTrait).to.be.a('function')
})

it('should return the first row from the database as model instance', function * () {
let query = null
class User extends Model {
static boot () {
super.boot()
this.onQuery((q) => { query = q })
}
}
User.bootIfNotBooted()
yield User.first()
expect(queryHelpers.formatQuery(query.sql)).to.equal(queryHelpers.formatQuery('select * from "users" limit ?'))
expect(queryHelpers.formatBindings(query.bindings)).deep.equal(queryHelpers.formatBindings([1]))
})

it('should return the last row from the database as model instance', function * () {
let query = null
class User extends Model {
static boot () {
super.boot()
this.onQuery((q) => { query = q })
}
}
User.bootIfNotBooted()
yield User.last()
expect(queryHelpers.formatQuery(query.sql)).to.equal(queryHelpers.formatQuery('select * from "users" order by "id" desc limit ?'))
expect(queryHelpers.formatBindings(query.bindings)).deep.equal(queryHelpers.formatBindings([1]))
})
})
})

0 comments on commit 2a74d6e

Please sign in to comment.