How i can return only the latest object in my relationship

I have 4 tables:
Users, Companies, Segments, Segment_screens and Screens.

I’m trying to fetch all the screens from a user based in your companies, companies have a segment and this segment have many screens.

I try this way:

const permissionsUser = await User.query()

      .where('id', userLogged.id)

      .with('companies.segment.screens')

      .fetch()

Is returning the result that i expect, but is returning the data of this user, your companies, the segment of this companie and last, the screens of this segment. I need only the “screens” array object. Someone can help me?

There’s other way to fetch this data with only the screens object?

You should look at https://adonisjs.com/docs/4.1/relationships#_many_through

or

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

const posts = user.getRelated('posts')
1 Like

Hi, i tried:

const userCompanie = await User.query()
      .with('companies')
      .where('users.id', request.params.user_id)
      .fetch()

    const companies = userCompanie.getRelated('companies')

But i’m receiving:

TypeError: userCompanie.getRelated is not a function

You can try this then:

const user = await User.find(request.params.user_id)
const companies = await user.load('companies')