首页 > 解决方案 > Adonis.js populate all with related tables data

问题描述

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 }

] }

标签: javascriptmysqlknex.jsadonis.js

解决方案


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

推荐阅读