lucid icon indicating copy to clipboard operation
lucid copied to clipboard

Choice fields to query inside relation when Eager Loading

Open alexhenriquepv opened this issue 6 years ago • 3 comments

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()

alexhenriquepv avatar Dec 13 '19 20:12 alexhenriquepv

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();

wobsoriano avatar Dec 13 '19 23:12 wobsoriano

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();

RomainLanz avatar Dec 18 '19 15:12 RomainLanz

Closing since not actionable with the new release.

RomainLanz avatar Jun 26 '20 19:06 RomainLanz