Get values after .with relation query without .toJSON method


#1

Maybe stupid question, but I just can’t figure this out :blush:

Let’s use this simple example…
I want to query first user, and populate his pets information from relation model.

const user = await User.query().with('pets').first()

Now, for some reason I want to console.log first pet name… But I can’t do something like:
console.log(user.pets[0])

After calling toJSON on user, user.pets[0] is possible to console log. How to achive this without serializing to json?

If you ask yourself why I don’t want to call toJSON, imagine if Pet model had get hidden method inside model which is hidding pet name…


#2

You can say user.getRelated('pets'), which returns a collection of pets. Also if you don’t want to output the JSON of users and pets together, it is better to lazy load the pets.

Eagerloading ( your way )

const user = await User.query().with('pets').first()
const pets = user.getRelated('pets')

Lazy loading

const user = await User.query().first()
const pets = await user.pets().fetch()

If your relationship is a hasMany, then pets will be an instance of Serializer. If it is hasOne then it will be an instance of Pet model.

Assuming it is a hasMany

// first pet => pets.rows[0] 
// second pet => pets.rows[1]

#3

Thank you virk :slight_smile:

.getRelated together with .rows was what I needed… Couldn’t find it in docs…

I hope docs will update soon :smiley:


#4

Just an info, you should use .paginate instead of .fetch as data can be a lot!