json-server icon indicating copy to clipboard operation
json-server copied to clipboard

How do you get an array of related data?

Open mr-scrpt opened this issue 9 months ago • 1 comments

Hi! There's a "table" with articles

 "articles": [
    {
      "id": "1",
      "title": "Test title 1",
      "subtitle": "subtitle 1",
      "userId": "1",
      "tagsId": ["1"]
    },
    {
      "id": "2",
      "title": "Test title 1",
      "subtitle": "subtitle 1",
      "userId": "1",
      "tagsId": ["1", "2"]
    }
  ],

There is a "table" with tags

 "tags": [
    { "id": "1", "name": "tab-it" },
    { "id": "2", "name": "tab-science" },
    { "id": "3", "name": "tab-economic" },

  ],

The result of a query on articles should contain an array of tags, the query looks like this

const response = await extra.api.get<IArticle[]>('/articles', {
      params: {
        _expand: ['user', 'tags'],
        _page: page,
        _limit: limit,
        _sort: sort,
        _order: order,
        q: search,
      },
    })

But in response, an article with id = 1 will have an object { "id": "1", "name": "tab-it" } in the tags field, and the article with id = 2 has no tags field. Can you please tell me how to get related data as an array of objects instead of a single object?

mr-scrpt avatar Oct 02 '23 15:10 mr-scrpt