Skip to content
Advertisement

How to get related field with typeorm?

In typeorm I run this code and the results are without lastApprover and managerApprover fields. I need those properties to be in the object. what I need to change to achieve that?

const b = connection.getRepository(Task);
const c = await b.find();

This is my code:

task.ts

import {
    Column,
    Entity,
    Index,
    JoinColumn,
    ManyToOne,
    PrimaryGeneratedColumn,
  } from "typeorm";
  import { User } from "./User";
  
  @Index("nc_unique_created_at", ["createdAt"], { unique: true })
  @Index("PK_task", ["id"], { unique: true })
  @Entity("task", { schema: "dbo" })
  export class Task {
    @PrimaryGeneratedColumn({ type: "int", name: "id" })
    id: number;
  
    @Column("date", { name: "created_at" })
    createdAt: Date;
  
    @Column("datetime", {
      name: "updated_at",
      nullable: true,
      default: () => "getdate()",
    })
    updatedAt: Date | null;
  
   
    @Column("varchar", { name: "name", nullable: true, length: 600 })
    name: string | null;
  
    @ManyToOne(() => User, (user) => user.procedures)
    @JoinColumn([{ name: "last_approver", referencedColumnName: "id" }])
    lastApprover: User;
  
    @ManyToOne(() => User, (user) => user.procedures3)
    @JoinColumn([
      { name: "manager_approver", referencedColumnName: "id" },
    ])
    managerApprover: User;
  
  }
  

user.ts:

import { Column, Entity, Index, OneToMany } from "typeorm";
import { Task } from "./Task";

@Index("PK_dbo.user", ["id"], { unique: true })
@Entity("user", { schema: "dbo" })
export class User {
  @Column("uniqueidentifier", {
    primary: true,
    name: "id",
    default: () => "newid()",
  })
  id: string;

  @Column("nvarchar", { name: "name", length: 80 })
  name: string;

  @Column("nvarchar", { name: "email", length: 255 })
  email: string;

  @Column("nvarchar", { name: "password" })
  password: string;

  @OneToMany(() => Task, (task) => task.lastApprover)
  tasks: Task[];

  @OneToMany(() => Task, (task) => task.managerApprover)
  task1: Task[];

}

Advertisement

Answer

Try to add relations

const b = connection.getRepository(Task);
const c = await b.find({relations: ['lastApprover', 'managerApprover']});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement