nestjs-typescript, typeorm, postgresql

halo teman-teman dan para suhu... ane lagi ngerjain project bootcamp menggunakan framework nestjs-typescript. sekarang ane lagi stuck pada satu masalah: mengambil kolom dari tabel lain pada controller dan service untuk method createEmp pada tabel Employee. ane bisa menambah data utk kolom lain, kecuali dari 3 kolom dari tabel lain:

1. empId dengan relasi empEmp, Employee berelasi dengan dirinya sendiri

2. userId dgn relasi empUser dari tabel Users

3. joroId dgn relasi empJoro dari tabel JobRole

semoga teman-teman dan suhu sedia membantu saya menyelesaikan ini...

berikut file yg ane punya:

1. controller:

@Post()
    public async createEmp(
        @Body('empNationalId') empNationalId: string,
        @Body('empBirthDate') empBirthDate: string,
        @Body('empMaritalStatus') empMaritalStatus: string,
        @Body('empGender') empGender: string,
        @Body('empHireDate') empHireDate: Date,
        @Body('empSalariedFlag') empSalariedFlag: string,
        @Body('empVacationHours') empVacationHours: number,
        @Body('empSickleaveHourse') empSickleaveHourse: number,
        @Body('empCurrentFlag') empCurrentFlag: number,
        @Body('empModifiedDate') empModifiedDate: Date,
        @Body('empId') empId: number,
        @Body('joroId') joroId: number,
        @Body('userId') userId: number,
    ) {
    return await this.employeeService.createEmp(
        empNationalId,
        empBirthDate,
        empMaritalStatus,
        empGender,
        empHireDate,
        empSalariedFlag,
        empVacationHours,
        empSickleaveHourse,
        empCurrentFlag,
        empModifiedDate,
        empId,
        joroId,
        userId,
    );
    }

2. service:

public async createEmp(
        empNationalId: string,
        empBirthDate: string,
        empMaritalStatus: string,
        empGender: string,
        empHireDate: Date,
        empSalariedFlag: string,
        empVacationHours: number,
        empSickleaveHourse: number,
        empCurrentFlag: number,
        empModifiedDate: Date,
        empId: number,
        joroId: number,
        userId: number,
        ) {
        try {
          const employee = await this.employeeRepo.findOne({ where: { empId: empId } });
          if (!employee) {
            throw new Error(`Employee with empId ${empId} not found`);
          }
          const jobRole = await this.jobRoleRepo.findOne({ where: { joroId: joroId } });
          if (!jobRole) {
            throw new Error(`Job role with joroId ${joroId} not found`);
          }
          const user = await this.usersRepo.findOne({ where: { userId: userId } });
          if (!user) {
            throw new Error(`User with userId ${userId} not found`);
          }
            const newEmp = this.employeeRepo.create({
            empNationalId: empNationalId,
            empBirthDate: empBirthDate,
            empMaritalStatus: empMaritalStatus,
            empGender: empGender,
            empHireDate: empHireDate,
            empSalariedFlag: empSalariedFlag,
            empVacationHours: empVacationHours,
            empSickleaveHourse: empSickleaveHourse,
            empCurrentFlag: empCurrentFlag,
            empModifiedDate: empModifiedDate,
            empEmp: employee,
            empJoro: jobRole,
            empUser: user,
          });
          await this.employeeRepo.save(newEmp);
        return {
            statusCode: 201,
            message: 'Data added successfully',
            data: {
                empNationalId: empNationalId,
                empEmp: employee
            },
          };
        } catch (error) {
          throw new Error(`Error adding data: ${error.message}`);
        }
        }

3. entities Employee:

import {
  Column,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
} from "typeorm";
import { JobRole } from "./JobRole";
import { Users } from "./Users";
import { EmployeeDepartmentHistory } from "./EmployeeDepartmentHistory";
import { EmployeePayHistory } from "./EmployeePayHistory";
import { PurchaseOrderHeader } from "./PurchaseOrderHeader";
import { WorkOrderDetail } from "./WorkOrderDetail";

@Index("employee_pkey", ["empId"], { unique: true })
@Entity("employee", { schema: "hr" })
export class Employee {
  @PrimaryGeneratedColumn({ type: "integer", name: "emp_id" })
  empId: number;

  @Column("character varying", {
    name: "emp_national_id",
    nullable: true,
    length: 25,
  })
  empNationalId: string | null;

  @Column("date", { name: "emp_birth_date", nullable: true })
  empBirthDate: string | null;

  @Column("character varying", {
    name: "emp_marital_status",
    nullable: true,
    length: 1,
  })
  empMaritalStatus: string | null;

  @Column("character varying", {
    name: "emp_gender",
    nullable: true,
    length: 1,
  })
  empGender: string | null;

  @Column("timestamp without time zone", {
    name: "emp_hire_date",
    nullable: true,
  })
  empHireDate: Date | null;

  @Column("character varying", {
    name: "emp_salaried_flag",
    nullable: true,
    length: 1,
  })
  empSalariedFlag: string | null;

  @Column("smallint", { name: "emp_vacation_hours", nullable: true })
  empVacationHours: number | null;

  @Column("smallint", { name: "emp_sickleave_hourse", nullable: true })
  empSickleaveHourse: number | null;

  @Column("smallint", { name: "emp_current_flag", nullable: true })
  empCurrentFlag: number | null;

  @Column("character varying", {
    name: "emp_photo",
    nullable: true,
    length: 255,
  })
  empPhoto: string | null;

  @Column("timestamp without time zone", {
    name: "emp_modified_date",
    nullable: true,
  })
  empModifiedDate: Date | null;

  @Column("character varying", {
    name: "emp_name",
    nullable: true,
    length: 100,
  })
  empName: string | null;

  @ManyToOne(() => Employee, (employee) => employee.employees, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "emp_emp_id", referencedColumnName: "empId" }])
  empEmp: Employee;

  @OneToMany(() => Employee, (employee) => employee.empEmp)
  employees: Employee[];

  @ManyToOne(() => JobRole, (jobRole) => jobRole.employees, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "emp_joro_id", referencedColumnName: "joroId" }])
  empJoro: JobRole;

  @ManyToOne(() => Users, (users) => users.employees, {
    onDelete: "CASCADE",
    onUpdate: "CASCADE",
  })
  @JoinColumn([{ name: "emp_user_id", referencedColumnName: "userId" }])
  empUser: Users;

  @OneToOne(
    () => EmployeeDepartmentHistory,
    (employeeDepartmentHistory) => employeeDepartmentHistory.edhiEmp
  )
  employeeDepartmentHistory: EmployeeDepartmentHistory;

  @OneToMany(
    () => EmployeePayHistory,
    (employeePayHistory) => employeePayHistory.ephiEmp
  )
  employeePayHistories: EmployeePayHistory[];

  @OneToMany(
    () => PurchaseOrderHeader,
    (purchaseOrderHeader) => purchaseOrderHeader.poheEmp
  )
  purchaseOrderHeaders: PurchaseOrderHeader[];

  @OneToMany(
    () => WorkOrderDetail,
    (workOrderDetail) => workOrderDetail.wodeEmp
  )
  workOrderDetails: WorkOrderDetail[];
}

avatar Nugrahar
@Nugrahar

3 Kontribusi 1 Poin

Diperbarui 1 tahun yang lalu

1 Jawaban:

<div>Saya bisa membantu Anda dengan ini.<br><br>Masalahnya adalah Anda tidak melewatkan parameter empId, joroId, dan userId ke dalam metode createEmp() di controller Anda. Anda perlu melakukan ini agar dapat membuat catatan karyawan baru di database.<br><br>Berikut ini adalah kode terbaru untuk controller Anda:<br><br></div><pre>@Post() public async createEmp( @Body('empNationalId') empNationalId: string, @Body('empBirthDate') empBirthDate: string, @Body('empMaritalStatus') empMaritalStatus: string, @Body('empGender') empGender: string, @Body('empHireDate') empHireDate: Date, @Body('empSalariedFlag') empSalariedFlag: string, @Body('empVacationHours') empVacationHours: number, @Body('empSickleaveHourse') empSickleaveHourse: number, @Body('empCurrentFlag') empCurrentFlag: number, @Body('empModifiedDate') empModifiedDate: Date, @Body('empId') empId: number, @Body('joroId') joroId: number, @Body('userId') userId: number, ) { return await this.employeeService.createEmp( empNationalId, empBirthDate, empMaritalStatus, empGender, empHireDate, empSalariedFlag, empVacationHours, empSickleaveHourse, empCurrentFlag, empModifiedDate, empId, joroId, userId, ); }</pre><div><br>Berikut ini adalah kode terbaru untuk service Anda:<br><br><br></div><pre>public async createEmp( empNationalId: string, empBirthDate: string, empMaritalStatus: string, empGender: string, empHireDate: Date, empSalariedFlag: string, empVacationHours: number, empSickleaveHourse: number, empCurrentFlag: number, empModifiedDate: Date, empId: number, joroId: number, userId: number, ) { try { const employee = await this.employeeRepo.findOne({ where: { empId: empId } }); if (!employee) { throw new Error(Karyawan dengan empId ${empId} tidak ditemukan); } const jobRole = await this.jobRoleRepo.findOne({ where: { joroId: joroId } }); if (!jobRole) { throw new Error(Peran pekerjaan dengan joroId ${joroId} tidak ditemukan); } const user = await this.usersRepo.findOne({ where: { userId: userId } }); if (!user) { throw new Error(Pengguna dengan userId ${userId} tidak ditemukan); } const newEmp = this.employeeRepo.create({ empNationalId: empNationalId, empBirthDate: empBirthDate, empMaritalStatus: empMaritalStatus, empGender: empGender, empHireDate: empHireDate, empSalariedFlag: empSalariedFlag, empVacationHours: empVacationHours, empSickleaveHourse: empSickleaveHourse, empCurrentFlag: empCurrentFlag, empModifiedDate: empModifiedDate, empEmp: employee, empJoro: jobRole, empUser: user, }); await this.employeeRepo.save(newEmp); return { statusCode

: 201, message: 'Data berhasil ditambahkan', data: { empNationalId: empNationalId, empEmp: employee }, }; } catch (error) { throw new Error(Error menambahkan data: ${error.message}); } }</pre><div><br>Semoga ini membantu!</div>

avatar adamajalah27
@adamajalah27

119 Kontribusi 40 Poin

Dipost 1 tahun yang lalu

Login untuk ikut Jawaban