Problem with Lazy Eager Loading


#1

Hi.
I’m using Adonis as API for Vuetify. I have a Feed Model than belongsTo a FeedType.

Feed.js

  type(){
    return this.belongsTo(
      'App/Models/FeedType',
      'feedtype_id')
  }

FeedType.js

  feeds(){
    return this.hasMany(
      'App/Models/Feed',
      'id',
      'feedtype_id')
  }

This works well and I get the information in queries with no problem.

Now I want to send all the Feed information in a specific format:

async show ({params, response}){

    const feed = await Feed.findByOrFail('slug',params.id)

    await feed.load('type')

    const result = {
      category:feed.type.slug,
      content:feed.feed,
      active:feed.is_active,
      comment:feed.allows_comments,
    }

    response.send(result)

  }

With this code i get all the fields but category. If I put feed.type there is no info either.

If I send response.send(feed) I get all the information of the feed, including the type.

What I’m missing?


#2

Hey @jorgeyoma! :wave:

This is because your relation is loaded under the private variable $relations. You can access it by using feed.getRelated('type').slug.

You can also use the method toJSON() that will call the serializer and return a JSON. Then you should be able to use feed.type.slug.

More on this: