Search code examples
node.jspostgresqlbookshelf.js

How to join/populate 3 tables with Bookshelf in Node.js


[This is different from already asked question]

I have 3 tables book, chapter, paragraph.

Book related to chapter.(one to many)

Chapter related to Paragraph(one to many)

How can I query Book and get related Chapters and related Paragraph ? Looking for something like nested withRelated

Expected output

[
  {
    "book1Info": "",
    "Chapters": [
      {
        "chaptor1Info": "",
        "Paragraphes": [
          {
            "page1": ""
          },
          {
            "page2": ""
          }
        ]
      },
      {}
    ]
  },
  {}
]

I have read docs and tried withRelated without success


Solution

  • I couldn't find it on Bookshelf.js documentation but found something related on github issues page which helped to figure it out-

    You can use withRelated and provide nested tables with dot.

    e.g. -

    withRelated: ['Books.Chapters']

    OR even

    withRelated: ['Books.Chapters.paragraphs']