How to fetch single row using withGraphJoined?

Viewed 164

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

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

Related