Return an object instead of an array in a many to many relationship


Hi guys,

I have this many to many relationship:

const Users = await User.query()
  .with('groups', (builder) => builder.first())
  .then((users) => users.toJSON())

// ...

But when I try to do that, I get an error.
Then, I tried to:

const Users = await User.query()
  .with('groups', (builder) => builder.limit(1))
  .then((users) => users.toJSON())

But then I get this output:

So, instead of getting an array with an object inside, how do I simply get an object in this query?

Thanks a lot.


That’s not possible. If the nature of the query is to return multiple rows, then it always be an array.

Also if you think that you will never have more than one related rows, then it’s not a many to many


All right. Thanks a lot, Virk. :blush: