-1

I use MySql, all relationships have been configured correctly in models and schemas:

I have 3 tables: 1. posts ( main ) 2. categories ( 1 post has 1 cat, 1 cat belongs to many posts ) 3. tags ( many-to-many )

Categories and tags both have "post_id" column relating to "id" column in posts table.

What is the best way to get all related data ( post data + post category data + post tags data ) ? ( for now I know I can get something like:

const post = await Post.find(params.id)
const category = await post.categories().fetch()
etc for every related table

I'm sure there must be better way.

I'd like result to be:

{ post data - name, text ...,

"category": { category data - name, text ... },

"tags": [ { tag1 data }, { tag2 data }

] }

2 Answers2

1
 const wantedData = await Post.query().where('id', params.id).with('categories').with('tags').fetch()
0

Yes, there is a better way to do this.

The Latest Adonis js Have the feature of the Query builder. You can perform almost all SQL queries using this. For Example

#select

Database
  .from('users')
  .select('id', 'username', 'email')

So There are many queries you can perform as your need. The following links will be very useful for you. Query builder Documentation