$ npx typeorm init --name typeormMigration --database postgres --module esm --express --docker
https://orkhan.gitbook.io/typeorm/docs/many-to-one-one-to-many-relations
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany(() => Photo, (photo) => photo.user)
photos: Relation<Photo>[]
}
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number
@Column()
url: string
@ManyToOne(() => User)
user: Relation<User>
}
$ docker exec -it typeormmigration-postgres-1 bash
root@5a503210d12d:/# psql -U test -d test
psql (14.5 (Debian 14.5-2.pgdg110+2))
Type "help" for help.
test=# SELECT * FROM photo p JOIN "user" u on u.id = p."userId";
id | url | userId | id | name
----+------------------+--------+----+---------
1 | me.jpg | 1 | 1 | Timber
2 | me-and-bears.jpg | 1 | 1 | Timber
3 | bears.jpg | 1 | 1 | Timber
4 | you.jpg | 2 | 2 | Phantom
(4 rows)
const photos = await AppDataSource
.getRepository(Photo)
.createQueryBuilder("photo")
.innerJoin("photo.user", "user")
.where("photo.id IN (:...photoIds)", { photoIds: [1, 2, 4] })
.getMany()
console.log(photos);
[
{
"id": 1,
"url": "me.jpg"
},
{
"id": 2,
"url": "me-and-bears.jpg"
},
{
"id": 4,
"url": "you.jpg"
}
]
const photos = await AppDataSource
.getRepository(Photo)
.createQueryBuilder("photo")
.innerJoinAndSelect("photo.user", "user")
.where("photo.id IN (:...photoIds)", { photoIds: [1, 2, 4] })
.getMany()
console.log(photos);
[
{
"id": 1,
"url": "me.jpg",
"user": {
"id": 1,
"name": "Timber"
}
},
{
"id": 2,
"url": "me-and-bears.jpg",
"user": {
"id": 1,
"name": "Timber"
}
},
{
"id": 4,
"url": "you.jpg",
"user": {
"id": 2,
"name": "Phantom"
}
}
]
const users = await AppDataSource
.getRepository(User)
.createQueryBuilder("user")
.innerJoin("user.photos", "photo")
.where("photo.id IN (:...photoIds)", { photoIds: [1, 2, 4] })
.getMany()
console.log(JSON.stringify(users, null, 4));
[
{
"id": 1,
"name": "Timber"
},
{
"id": 2,
"name": "Phantom"
}
]
const users = await AppDataSource
.getRepository(User)
.createQueryBuilder("user")
.innerJoinAndSelect("user.photos", "photo")
.where("photo.id IN (:...photoIds)", { photoIds: [1, 2, 4] })
.getMany()
console.log(JSON.stringify(users, null, 4));
[
{
"id": 1,
"name": "Timber",
"photos": [
{
"id": 1,
"url": "me.jpg"
},
{
"id": 2,
"url": "me-and-bears.jpg"
}
]
},
{
"id": 2,
"name": "Phantom",
"photos": [
{
"id": 4,
"url": "you.jpg"
}
]
}
]