Iqlas Uddin
Iqlas Uddin

Reputation: 187

Select specific columns in adonis JS using ORM

There is a way in Adonis JS using

Database.select('name','email').from('users')

Is there a way to achieve this using ORM?

const User = use('App/Models/User')

//wherever required

let users = User.find(key).fetch({'name', email'})

Something similar to what we use in Laravel.

User::find(1)->pluck('name'); or User::find(1)->get(['name']);

Upvotes: 0

Views: 5790

Answers (2)

Christopher Dosin
Christopher Dosin

Reputation: 1361

Adonis has also some helper methods for the query builder which are described in the docs like pluck. So to get the result you would have something like:

const result = await Database.from('users')
  .where('id', 1)
  .pluck('name');

return result;

Or another approach

const result = await User.query()
  .where('id', 1)
  .pluck('name')
  .first();

return result;

Upvotes: 1

Pepe
Pepe

Reputation: 381

The static method find in model returns this

return yield this.query().where(key, value).first()

so you can edit your query to this

yield User.query().where('id', key).select('name', 'email').first()

It will be the same that you are trying to do

Upvotes: 2

Related Questions