Search code examples
node.jsexpressknex.js

How to fetch rows related to the table I'm querying using Knex


I'm facing an issue with my program. If you could please provide a solution or refer me to the right source it would be great.

I'm going to explain my problem with an example.

Lets say I want to get a post from my database and the result looks like this:

{
    "id": 1,
    "name": "Post 1",
    "author_id": 1
}

My goal is to include within the result the details of the author. So the response would look like this:

{
    "id": 1,
    "name": "Post 1",
    "author": {
        "id": 1,
        "name": "Danny DeVito"
    }
}

I could currently achieve this with some code I wrote using a transaction. Is there a way to do this with an internal Knex function? If so, please provide an example. If not, is a transaction the most efficient way to do this?


Solution

  • Sadly I found the following:

    Short answer: No.

    With Knex, you can retrieve data the same as with SQL, which is record based, not object based

    Source

    However, after a bit of digging I found a package that can achieve something similar to Laravel's eager loading. It is called Objection.js and it allows me to keep my Knex.js migrations