简体   繁体   中英

select all many to many records alongside with parent table in one hit to database

I have a three table(Postgresql):

ModelA:
    model_a_id
    item1
    item2


ModelB:
    model_b_id
    item1
    item2


ModelA_ModelB:
    model_a_id foreign_key to ModelA
    model_b_id foreign_key to ModelB

Ok

I want to select All ModelA with all relation to ModelB.

what I want is:

[{
    Record1ModelA: {
        item1: 'A',
        item2: 'B',
        modelBList: [{
              Record1ModelB: {
                  item1: 'C',
                  item2: 'D'
              },
              Record2ModelB: {
                  item1: 'E',
                  item2: 'F'
              }
              ...
        }]
    },
    Record2ModelA: {
        item1: 'G',
        item2: 'H',
        modelBList: [{
              Record1ModelB: {
                  item1: 'I',
                  item2: 'G'
              },
              Record2ModelB: {
                  item1: 'K',
                  item2: 'L'
              }
              ...
        }]
    }
    ...
}]

Question :

  1. Can I make this result with a hit to the database?
  2. If yes, How can I achieve this result with SQL Query?

Ok, Finally, I found an answer to this question:

Answer is: json_agg in postgresql

SELECT ModelA.model_a_id, ModelA.item1, ModelA.item2, json_agg(mb.*)
FROM ModelA
LEFT JOIN ModelA_ModelB as mab on ModelA.model_a_id = mab.model_a_id
LEFT JOIN  ModelB as mb on mb.model_b_id = mab.model_b_id
GROUP BY ModelA.model_a_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM