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


#1

Hi guys,

I have this many to many relationship:

const Users = await User.query()
  .with('groups', (builder) => builder.first())
  .fetch()
  .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))
  .fetch()
  .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.


#2

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


#3

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