Search code examples
javascriptsqlnode.jstypescripttypeorm

get fields instead of object from relation (typeorm)


I am new to typeorm and when i want to retrieve a table that has a relation, the columns of that relation are retrieved in an object with the name of that table. Here is an example

import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany((type) => Photo, (photo) => photo.user)
    photos: Photo[]
}
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string

    @ManyToOne((type) => User, (user) => user.photos)
    user: User
}
const user = await createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne()

Result

{
    id: 1,
    name: "Timber",
    photos: [{
        id: 1,
        url: "me-with-chakram.jpg"
    }, {
        id: 2,
        url: "me-with-trees.jpg"
    }]
}

I want to get the fields of the relation at the same level as the fields of my table

Expected Result

{
   {
    id: 1,
    name: "Timber",
    id: 1,
    url: "me-with-chakram.jpg"
    }
   {
    id: 1,
    name: "Timber",
    id: 2,
    url: "me-with-trees.jpg"
    }
}

Is there an option to do this ? I didn't find anything in their docs


Solution

  • I tried using '*' and it worked

      const user = await createQueryBuilder("user")
            .leftJoinAndSelect("user.photos", "photo")
            .select('*')
            .where("user.name = :name", { name: "Timber" })
            .getOne();