Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To write an entity in TypeORM, you first need to create a class that describes the data structure of your entity. The class should be decorated with the @Entity() decorator from TypeORM, specifying the name of the entity's table as an argument. Inside the class, you define the columns of the table as properties of the class, with the appropriate data types and decorators to define their characteristics.

Here's an example of a simple entity class:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'users' })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  email: string;
}

In this example, we define an entity called User with four columns: id (auto-generated primary key), firstName, lastName, and email. Each column is defined as a property of the User class with the appropriate decorators from TypeORM.

To find data in TypeORM, you can use the QueryBuilder or Repository pattern. The QueryBuilder allows you to construct complex queries using a fluent API, while the Repository pattern provides a higher-level abstraction for interacting with your entities.

Here's an example of using the Repository pattern to find all users in the database:

import { getRepository } from 'typeorm';
import { User } from './user.entity';

async function getUsers() {
  const userRepository = getRepository(User);
  const users = await userRepository.find();
  return users;
}

In this example, we get a reference to the User repository using the getRepository() function, then call the find() method to retrieve all users from the database. The find() method returns a Promise that resolves to an array of User objects.