Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!