How to get the lastest record of a relationship?

I need to get the last quotation register of each currency.

I was trying doing this:

    let moedas = Moeda.query().with('moedacotacao', builder => {
      builder.pickInverse();
    });

    return await moedas.paginate(page, limit);

But by this way it returns only the last register of the table ‘moedacotacao’

If i dont use the function with builder param, then i will receive all registers of the table, and i want to avoid this.

I just want the last register in ‘moedacotacao’ of each ‘moeda’

How is the right approach to do that?

1 Like

Hi @Keony1!

I think I’d set up separate relation with it, something like this:

// Pseudocode in Moeda.js
latestMoedacotacao () {
  return this.hasMany('App/Models/Moedacotacao')
    .orderBy('id', 'DESC')
    .first()
}

And then query like this:

Moeda.query().with('latestMoedacotacao')
3 Likes

Hello @McSneaky, how are u?

So, i’ve tried to do what you suggested but i receive this response:

TypeError
relationInstance.eagerLoad is not a function

Did you solve it? I’m getting the same issue.

This answer, How to get the lastest record of a relationship?, should solve it.

I got the same issue TypeError: relationInstance.eagerLoad is not a function

My bad jup. If you want to use it with with() remove .first() in relationship definition and add it to builder

2 Likes