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.
For the introductory video on PostgreSQL functions, check out https://www.youtube.com/watch?v=MJZCCpCYEqk Sometimes we have a collection ...
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.
For the introductory video on PostgreSQL functions, check out https://www.youtube.com/watch?v=MJZCCpCYEqk Sometimes we have a collection ...