drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
21.47k stars 486 forks source link

[FEATURE]: Unwrap chained relations in `with` operator if `columns` is empty or `false` #2462

Open TheGrinch00 opened 3 weeks ago

TheGrinch00 commented 3 weeks ago

Describe what you want

Let's say we have a N:N relation between tables A and B through the A_to_B table.

When I query A and want all the B without any column from A_to_B, what I get is this

{
   id: number;
   someOtherAColumn: string;
   a_to_b: {
      b: {
          id: number;
          someOtherBColumn: string;
      }
   }[]
}[]

Instead it would be better in my opinion to have a result that looks something like this:

{
   id: number;
   someOtherAColumn: string;
   b: {
       id: number;
       someOtherBColumn: string;
   }[]
}[]

To get this result, you would have to explicitly state to not be interested in any of the middle table columns like this:

const myARowsWithB = db.query.A.findMany({
    with: {
        aToB: {
            columns: false, // Or even columns: {}
            with: {
                b: true,
            }
        },
    }
})

// Now you can do this
myARowsWithB[0].b.map(...)

This behaviour could be extended not only to a N:N relation but in general to any chain of relations when you are only interested in the very last JOINed table like this:

const myARowsWithD = await db.query.A.findMany({
    with: {
        aToB: {
            columns: false,
            with: {
                b: {
                    columns: false,
                    with: {
                        c: {
                            columns: false,
                            with: {
                                 d: true,
                             },
                        },
                    },
                },
            }
        },
    }
})

// Now you can do this
myARowsWithD[0].d.map(...)