Как создать связь между столбцом `json` и столбцом` int` (id) в Hasura + Postgres? - PullRequest
1 голос
/ 26 февраля 2020

У меня есть 2 таблицы users и post

Таблица users имеет столбцы id и post, столбец содержит массив вида [1, 2, 3, 4, 5] - где 1, 2, 3, 4, 5 id в таблице post

В таблице posts следующие столбцы id и text

Таблица users:

https://i.stack.imgur.com/ywdS7.png

Таблица posts:

https://i.stack.imgur.com/IBdpb.png

в Хасуре сделана связь массива

https://i.stack.imgur.com/311sd.png

Далее я сделал следующий запрос

{
  users_test {
    postz {
      id
    }
  }
}

Я хотел бы получить в ответ такие данные:

    postz: [
       {
         text: 'qwe'
       },
       {
         text: 'sdf'
       }
    ]

Но с такой просьбой я получаю след. ошибка:

{
  "errors": [
    {
      "extensions": {
        "internal": {
          "statement": "SELECT  coalesce(json_agg(\"root\" ), '[]' ) AS \"root\" FROM  (SELECT  row_to_json((SELECT  \"_5_e\"  FROM  (SELECT  \"_4_root.ar.root.postz\".\"postz\" AS \"postz\"       ) AS \"_5_e\"      ) ) AS \"root\" FROM  (SELECT  *  FROM \"public\".\"users_test\"  WHERE ('true')     ) AS \"_0_root.base\" LEFT OUTER JOIN LATERAL (SELECT  coalesce(json_agg(\"postz\" ), '[]' ) AS \"postz\" FROM  (SELECT  row_to_json((SELECT  \"_2_e\"  FROM  (SELECT  \"_1_root.ar.root.postz.base\".\"id\" AS \"id\"       ) AS \"_2_e\"      ) ) AS \"postz\" FROM  (SELECT  *  FROM \"public\".\"posts\"  WHERE ((\"_0_root.base\".\"post\") = (\"id\"))     ) AS \"_1_root.ar.root.postz.base\"      ) AS \"_3_root.ar.root.postz\"      ) AS \"_4_root.ar.root.postz\" ON ('true')      ) AS \"_6_root\"      ",
          "prepared": true,
          "error": {
            "exec_status": "FatalError",
            "hint": "No operator matches the given name and argument type(s). You might need to add explicit type casts.",
            "message": "operator does not exist: json = integer",
            "status_code": "42883",
            "description": null
          },
          "arguments": [
            "(Oid 114,Just (\"{\\\"x-hasura-role\\\":\\\"admin\\\"}\",Binary))"
          ]
        },
        "path": "$",
        "code": "unexpected"
      },
      "message": "postgres query error"
    }
  ]
}

Что я делаю не так и как я могу это исправить?

1 Ответ

3 голосов
/ 26 февраля 2020

Несколько предложений:

  1. Насколько я могу судить, в вашем запросе есть некоторые опечатки. Попробуйте:
{
  users {
    id
    posts {
      text
    }
  }
}
Вам не нужен столбец post в таблице users. Вам просто нужен столбец user_id в таблице posts и ограничение внешнего ключа от таблицы posts к таблице users с использованием столбцов user_id и id таблиц соответственно. Проверьте документы здесь:

https://docs.hasura.io/1.0/graphql/manual/schema/relationships/create.html#step -3-create-an-array-Relations

https://docs.hasura.io/1.0/graphql/manual/schema/relationships/database-modelling/one-to-many.html

Если по какой-то причине вам нужен столбец массива post, вы можете использовать вычисляемые поля для создания «взаимосвязи» между массивом json и идентификатором другой таблицы.

https://docs.hasura.io/1.0/graphql/manual/schema/computed-fields.html#table -computed-fields

Ваша функция будет:

  • Взять в столбец json массив

  • Извлечение идентификатора

  • Возврат select * из таблицы, где идентификатор в идентификаторах

Пример:

https://jsonb-relationships-hasura.herokuapp.com/console/api-explorer

Определение вычисленного поля в: https://jsonb-relationships-hasura.herokuapp.com/console/data/schema/public/tables/authors/modify

Выполнить эти запросы:

# Get list of articles for each author
query {
  authors {
    id
    name
    articles
  }
}
# Get actual articles for each author
query {
  authors {
    id
    name
    owned_articles {
      id
      title
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...