Drizzle | 관련된 자식 행이 하나 이상 있는 부모 행 선택하기
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:
이 가이드에서는 관련된 자식 행이 하나 이상 있는 부모 행을 선택하는 방법을 설명합니다. 아래에는 스키마 정의와 해당 데이터베이스 데이터 예제가 있습니다.
import { integer, pgTable, serial, text } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull(),
});
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content').notNull(),
userId: integer('user_id').notNull().references(() => users.id),
});
users.db
posts.db
+----+------------+----------------------+
| id | name | email |
+----+------------+----------------------+
| 1 | John Doe | john_doe@email.com |
+----+------------+----------------------+
| 2 | Tom Brown | tom_brown@email.com |
+----+------------+----------------------+
| 3 | Nick Smith | nick_smith@email.com |
+----+------------+----------------------+
관련된 자식 행이 하나 이상 있는 부모 행을 선택하고 자식 데이터를 가져오려면 .innerJoin()
메서드를 사용할 수 있습니다.
import { eq } from 'drizzle-orm';
import { users, posts } from './schema';
const db = drizzle(...);
await db
.select({
user: users,
post: posts,
})
.from(users)
.innerJoin(posts, eq(users.id, posts.userId))
.orderBy(users.id);
select users.*, posts.* from users
inner join posts on users.id = posts.user_id
order by users.id;
// 결과 데이터, id가 2인 사용자는 게시물이 없으므로 포함되지 않음
[
{
user: { id: 1, name: 'John Doe', email: 'john_doe@email.com' },
post: {
id: 1,
title: 'Post 1',
content: 'This is the text of post 1',
userId: 1
}
},
{
user: { id: 1, name: 'John Doe', email: 'john_doe@email.com' },
post: {
id: 2,
title: 'Post 2',
content: 'This is the text of post 2',
userId: 1
}
},
{
user: { id: 3, name: 'Nick Smith', email: 'nick_smith@email.com' },
post: {
id: 3,
title: 'Post 3',
content: 'This is the text of post 3',
userId: 3
}
}
]
관련된 자식 행이 하나 이상 있는 부모 행만 선택하려면 exists()
함수를 사용한 서브쿼리를 다음과 같이 사용할 수 있습니다.
import { eq, exists, sql } from 'drizzle-orm';
const sq = db
.select({ id: sql`1` })
.from(posts)
.where(eq(posts.userId, users.id));
await db.select().from(users).where(exists(sq));
select * from users where exists (select 1 from posts where posts.user_id = users.id);
// 결과 데이터, id가 2인 사용자는 게시물이 없으므로 포함되지 않음
[
{ id: 1, name: 'John Doe', email: 'john_doe@email.com' },
{ id: 3, name: 'Nick Smith', email: 'nick_smith@email.com' }
]