프로그래밍/NextJS

typeorm 메서드 총정리

타코코딩 2024. 3. 28. 23:59

 

  @Post('sample')
  async sample() {
    const user1 = this.userRepository.create({
      email: 'test@jiwon.com',
    });

    const user2 = await this.userRepository.save({
      email: 'test@jiwon.com',
    });

    //preload는 불러오고 대체함 하지만 저장하지는 않음
    const user3 = await this.userRepository.preload({
      id: 101,
      email: 'test@jiwon.co.kr',
    });

    //삭제하기
    await this.userRepository.delete(101);

    // id 1인 count컬럼 1을 올림
    await this.userRepository.increment(
      {
        id: 1,
      },
      'count',
      1,
    );

    // count  row갯수세기
    const count = await this.userRepository.count({
      where: {
        email: ILike('%0%'),
      },
    });

    //sum
    const sum = await this.userRepository.sum('count', {
      email: ILike('%0%'),
    });

    // average

    const average = await this.userRepository.average('count', {
      id: LessThan(4),
    });

    //최소값
    const min = await this.userRepository.minimum('count', {
      id: LessThan(4),
    });

    // 최대값
    const max = await this.userRepository.maximum('count', {
      id: LessThan(4),
    });
    // find
    const users = await this.userRepository.find({});
    //findOne
    const userOne = await this.userRepository.find({
      where: {
        id: 3,
      },
    });

    const pageNation = await this.userRepository.findAndCount({
      take: 3,
    });

    return user2;
  }

1. save(entity)

  • 설명: 하나 또는 여러 엔티티를 데이터베이스에 저장합니다. 엔티티가 이미 존재한다면(즉, 이미 데이터베이스에 저장된 엔티티와 동일한 ID를 가지고 있다면), 업데이트를 수행합니다.
  • 사용 예: 새 사용자를 생성하거나 기존 사용자의 정보를 업데이트할 때 사용됩니다.

2. find(options)

  • 설명: 조건에 맞는 모든 엔티티를 찾아 배열로 반환합니다. options 객체를 통해 다양한 조건(예: WHERE 절, 정렬, 제한, 조인 등)을 지정할 수 있습니다.
  • 사용 예: 특정 조건을 만족하는 모든 상품을 찾을 때 사용됩니다.

3. findOne(id | options)

  • 설명: 주어진 ID 또는 조건에 따라 하나의 엔티티를 찾아 반환합니다. 엔티티를 찾지 못하면 null을 반환합니다.
  • 사용 예: 특정 ID를 가진 사용자를 찾을 때 사용됩니다.

4. remove(entity)

  • 설명: 하나 또는 여러 엔티티를 데이터베이스에서 삭제합니다. 삭제하려는 엔티티는 이미 데이터베이스에 존재해야 합니다.
  • 사용 예: 더 이상 필요 없어진 사용자 정보를 삭제할 때 사용됩니다.

5. create(query)

  • 설명: 새 엔티티 인스턴스를 생성하지만, 데이터베이스에는 저장하지 않습니다. 이 메서드는 주어진 객체나 객체 배열을 기반으로 엔티티의 새 인스턴스를 만듭니다.
  • 사용 예: 새 사용자 정보를 입력 받아 엔티티 인스턴스를 생성할 때 사용됩니다.

6. update(criteria, partialEntity)

  • 설명: 주어진 조건에 맞는 엔티티를 찾아, 제공된 객체의 값을 사용하여 업데이트합니다. 이 메서드는 엔티티의 부분적인 업데이트를 지원합니다.
  • 사용 예: 사용자의 이메일 주소를 업데이트할 때 사용됩니다.

7. createQueryBuilder(alias)

  • 설명: SQL 쿼리를 보다 세밀하게 조작할 수 있는 쿼리 빌더를 생성합니다. alias는 반환될 엔티티에 대한 별칭입니다.
  • 사용 예: 복잡한 조인 쿼리나 서브 쿼리를 사용해야 할 때 사용됩니다.

8. transaction(runInTransaction)

  • 설명: 데이터베이스 트랜잭션을 시작합니다. runInTransaction 함수 내에서 실행되는 모든 데이터베이스 연산은 하나의 트랜잭션으로 묶입니다.
  • 사용 예: 여러 데이터 변경 작업을 하나의 작업 단위로 처리해야 할 때 사용됩니다.