Lucid: Choice fields to query inside relation when Eager Loading

Created on 13 Dec 2019  路  3Comments  路  Source: adonisjs/lucid

When I query model using Eager Loading, ex:

const user = await User.query().with('posts').fetch()

I wish I could choose only some fields.

In this sample, I will get all _postModel_ fields but only _post.title_ interests me.
Something like this:

const user = await User .query() .with('posts', builder => { builder.select('title') }) .fetch()

Enhancement

Most helpful comment

You also need to define the relation field.

const user = await User.query()
    .with('posts', builder => {
        builder.select('user_id', 'title'); // user_id is needed
    })
    .fetch();

All 3 comments

You also need to define the relation field.

const user = await User.query()
    .with('posts', builder => {
        builder.select('user_id', 'title'); // user_id is needed
    })
    .fetch();

Hey @alexhenriquepv, @sorxrob! 馃憢

The current solution is to use what @sorxrob proposed.

I believe we could make it more elegant by copying what Laravel has done.

Before

const user = await User.query()
  .with('posts', builder => {
    builder.select('user_id', 'title'); // user_id is needed
  })
  .fetch();

After

const user = await User.query()
  .with('posts:title')
  .fetch();

Closing since not actionable with the new release.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hectorgrecco picture hectorgrecco  路  3Comments

moar55 picture moar55  路  4Comments

vrwebdesign picture vrwebdesign  路  3Comments

italoiz picture italoiz  路  6Comments

watzon picture watzon  路  3Comments