diff --git a/src/Lucid/Model/index.js b/src/Lucid/Model/index.js index f277ecb9..e083acee 100644 --- a/src/Lucid/Model/index.js +++ b/src/Lucid/Model/index.js @@ -806,6 +806,32 @@ class Model { static pickInverse (limit = 1) { return this.query().orderBy(this.primaryKey, 'desc').limit(limit).fetch() } + + /** + * Returns an array of ids. + * + * Note: this method doesn't allow eagerloading relations + * + * @method ids + * + * @return {Array} + */ + static ids () { + return this.query().ids() + } + + /** + * Returns an array of ids. + * + * Note: this method doesn't allow eagerloading relations + * + * @method ids + * + * @return {Array} + */ + static pair (lhs, rhs) { + return this.query().pair(lhs, rhs) + } } Model.hydrate() diff --git a/src/Lucid/QueryBuilder/index.js b/src/Lucid/QueryBuilder/index.js index 9b1b7978..69796816 100644 --- a/src/Lucid/QueryBuilder/index.js +++ b/src/Lucid/QueryBuilder/index.js @@ -163,6 +163,37 @@ class QueryBuilder { this.model.$hooks.after.exec('find', modelInstance) return modelInstance } + + /** + * Returns an array of primaryKeys + * + * @method ids + * + * @return {Array} + */ + async ids () { + const rows = this.query + return rows.map((row) => row[this.model.primaryKey]) + } + + /** + * Returns a pair of lhs and rhs. This method will not + * eagerload relationships. + * + * @method pair + * + * @param {String} lhs + * @param {String} rhs + * + * @return {Object} + */ + async pair (lhs, rhs) { + const collection = await this.fetch() + return _.transform(collection.rows, (result, row) => { + result[row.$attributes[lhs]] = row.$attributes[rhs] + return result + }, {}) + } } module.exports = QueryBuilder diff --git a/test/unit/lucid.spec.js b/test/unit/lucid.spec.js index f81aa132..26862c83 100644 --- a/test/unit/lucid.spec.js +++ b/test/unit/lucid.spec.js @@ -726,4 +726,37 @@ test.group('Model', (group) => { assert.equal(users.size(), 1) assert.equal(users.first().$attributes.username, 'nikk') }) + + test('return an array of ids from the database', async (assert) => { + class User extends Model { + } + + User._bootIfNotBooted() + + await ioc.use('Adonis/Src/Database').table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) + const userIds = await User.ids() + assert.deepEqual(userIds, [1, 2]) + }) + + test('return an array of ids from the database', async (assert) => { + class User extends Model { + } + + User._bootIfNotBooted() + + await ioc.use('Adonis/Src/Database').table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) + const userIds = await User.ids() + assert.deepEqual(userIds, [1, 2]) + }) + + test('return a pair of key/values from the database', async (assert) => { + class User extends Model { + } + + User._bootIfNotBooted() + + await ioc.use('Adonis/Src/Database').table('users').insert([{ username: 'virk' }, { username: 'nikk' }]) + const users = await User.pair('id', 'username') + assert.deepEqual(users, { 1: 'virk', 2: 'nikk' }) + }) })