Search code examples
postgraphile

Make View in Postgraphile Return Nested Objects


In Postgraphile 4 I have a view that joins two tables, which amounts to:

SELECT
  table1.fieldA,
  table1.fieldB,
  table2.fieldA AS table2_fieldA,
  table2.fieldB AS table2_fieldB
FROM table1
  JOIN table.table2_id = table2.id

At one point, this view was returning GraphQL results like:

 {
    fieldA,
    fieldB,
    table2 {
      fieldA,
      fieldB
    }
 }

But then I changed something (not sure what), and now I instead get results:

 {
    fieldA,
    fieldA,
    table2_fieldA,
    table2_fieldB
 }

Can anyone explain how I can get the results to return as a nested object again? I'm not sure what I did to make the results return un-nested, but whatever it was I just want to undo it.


Solution

  • Newer (and more accurate answer). After working with the amazing Benjie on the PostGraphile team, we managed to figure out that I had (by accident) done something neither of us even realized was possible.

    The "magic trick" was that you have to select an entire "table record" in your query. In other words, my query must have actually been something like:

    SELECT
      table1.fieldA,
      table1.fieldB,
      table2
    FROM table1, table2
    WHERE table1.table2_id = table2.id
    

    When you select an entire table record (eg. table2 above, without a column selection) PostGraphile returns it in the API as a proper object endpoint.

    Thanks again Benjie!