3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeORMでattributeを指定して階層構造データを取得する

Last updated at Posted at 2021-04-25

目的

SELECT u.id, u.name, p.name
FROM users u
INNER JOIN posts p
ON u.id = p.user_id
WHERE p.id = 1;

というsqlを発行して、JS実行時に以下のようなオブジェクトを取得したい。

{
  id: 1,
  name: 'Yamada Taro',
  posts: [
    { name: '記事1' },
  ],
}

Partial Selection

import {getRepository} from "typeorm";

const user = await getRepository(User)
    .createQueryBuilder('user')
    .select([
      'user.id',
      'user.name',
      'post.name',
    ])
    .innerJoin('posts', 'post')
    .where('post.id = :id', { id: 1 })
    .getOne();

によって、attributeを指定しつつ階層構造を保持したobjectを取得できる。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?