Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

279
Visualizações
How to fetch single row using withGraphJoined?

There are two tables users and activities.

I am able to join these using withGraphJoined. The response json is like this,

[
  {
    user: 'first',
    activity: [{ type: 'act1' }, { type: 'act2' }],
  },

  {
    user: 'second',
    activity: [{ type: 'act3' }, { type: 'act2' }],
  },
];

Now i want to fetch only the first activity and make current array into first activity object. {user:"second", activity:{type:"act3}}

I tried this but still i get all the activity in array.

User.query()
  .withGraphJoined('activity')
  .modifyGraph('activity', (builder) => builder.first());
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This depends on how you define the relationship if you want it to return a single object then the relation should use Model.HasOneRelation or Model.BelongsToOneRelation

however if you just want to return a single activity from many you can limit the results

.modifyGraph('activity', (builder) => builder.orderBy('created_at', 'desc').limit(1));

but it will still return an array with one item that you can access by activity[0] the only way i can think of is if you manually map this first item in your then like

.then(user => {
    user.activity = user.activity[0] ? user.activity[0] : {}
    res.json(user)
})

to be on the safe side, you can check if the item exists first to avoid null error

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda