[Solved] Drizzle ORM How do I include one side of a many to many as an array of objects in a select many? – Drizzle

by
Alexei Petrov
drizzle node.js postgresql react-typescript

Quick Fix: Use the with clause to include the platforms table as an array of objects in the select many query. Access the platform property inside each object to get the platform details.

The Problem:

Given three tables with a many-to-many relationship, Games, GamesToPlatforms, and Platforms, how do you retrieve all Games along with an array of associated Platform objects using Drizzle ORM’s relations feature?

The Solutions:

Solution 1: Use Drizzle ORM’s Relational Queries API

To query all `Games` so that it has a key of `platforms` that is an array of platform objects associated with it threw the join table, you can use Drizzle ORM’s Relational Queries API as follows:

const result: Response = await db.query.GamesTable.findMany({
	with: {
		platforms: {
			columns: {},
			with: {
				platform: true
			}
		}
	}
})

This will return an array of objects with the following shape:

type Response = {
    id: string;
    name: string;
    backgroundImage: string;
    platforms: {
        platform: {
            id: number;
            name: string;
            imageBackground: string;
        };
    }[];
}[]

You will still need to access the junction table and then the platform property inside each object because, for now, there is no other way to do it in Drizzle ORM’s Relational Queries API. You can always map it to any shape you need, but I would recommend using it as it is.

Q&A

How to include array of objects as result of many relationship?

Use with to specify nested attributes.

Video Explanation:

The following video, titled "Call Postgres functions from JavaScript with RPC - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

For the introductory video on PostgreSQL functions, check out https://www.youtube.com/watch?v=MJZCCpCYEqk Sometimes we have a collection ...