user15254140
user15254140

Reputation:

how to get relationship data in adonis js

I have a relational model in adonis that I want to retrieve the data (Post belongs to Category). I've set up the relationship in both of migration and model,

But when I try to get the category name from the first Post with

const posts = await Post.first()
return posts?.category.name

it returns "cannot read data" even though I've seeded the database with the correct data

Upvotes: 1

Views: 568

Answers (1)

VENKATESH CHAVVAKULA
VENKATESH CHAVVAKULA

Reputation: 323

in Model we need to define a releation

class Post extends Model {

category() {
        return this.belongsTo('App/Models/Category', 'category_id').select('id', 'name');
}
}

Following code is used to get data of relation

 let post = await Post.query().with('category').first()

Upvotes: 0

Related Questions