📜  crud typeorm 关系 (1)

📅  最后修改于: 2023-12-03 15:00:03.981000             🧑  作者: Mango

CRUD with TypeORM Relationships

TypeORM is an Object Relational Mapping (ORM) framework that can be used with TypeScript or JavaScript. It makes it easy to work with databases by providing a layer of abstraction over the database operations.

One of the powerful features of TypeORM is its support for relationships between entities. In this guide, we will explore how to perform CRUD (Create, Read, Update, Delete) operations with TypeORM relationships.

Setting up the Database Connection

Before we get started, we need to set up the database connection. TypeORM supports multiple database systems including MySQL, PostgreSQL, SQLite, and more. For this example, we will use SQLite.

To set up the database connection, add the following configuration to a TypeORM config file (ormconfig.json):

{
  "type": "sqlite",
  "database": "database.sqlite",
  "entities": ["src/entities/*.ts"],
  "synchronize": true
}

This configuration specifies SQLite as the database and the path to the database file. It also specifies where the entity files are located (src/entities/*.ts) and enables automatic schema synchronization.

Defining Entities with Relationships

Now that we have our database connection set up, we can define our entities. In this example, we will have two entities: User and Address. Each user can have one address, and an address can belong to multiple users.

Here's the code for the User entity:

import { Entity, Column, OneToOne, JoinColumn } from 'typeorm';
import { Address } from './address';

@Entity()
export class User {
  @Column({ primary: true })
  id: number;

  @Column()
  name: string;

  @OneToOne(() => Address)
  @JoinColumn()
  address: Address;
}

And here's the code for the Address entity:

import { Entity, Column, OneToMany } from 'typeorm';
import { User } from './user';

@Entity()
export class Address {
  @Column({ primary: true })
  id: number;

  @Column()
  street: string;

  @Column()
  city: string;

  @OneToMany(() => User, user => user.address)
  users: User[];
}

The User entity has a one-to-one relationship with the Address entity. We define this relationship using the @OneToOne decorator and specifying the target entity (Address). We also use the @JoinColumn decorator to specify the foreign key column name.

The Address entity has a one-to-many relationship with the User entity. We define this relationship using the @OneToMany decorator and specifying the target entity (User) and the inverse side of the relationship (user => user.address).

CRUD Operations

Now that we have our entities defined, we can perform CRUD operations with them.

Creating Entities

To create a new User entity, we can simply create a new instance of the User class and set the properties:

const user = new User();
user.id = 1;
user.name = 'John Smith';

To create a new Address entity, we can do the same:

const address = new Address();
address.id = 1;
address.street = '123 Main St';
address.city = 'Anytown';

To associate the User with the Address, we can simply set the address property:

user.address = address;

To save the entities to the database, we can use the getRepository function provided by TypeORM:

const userRepository = getRepository(User);
const addressRepository = getRepository(Address);

await userRepository.save(user);
await addressRepository.save(address);
Reading Entities

To read entities from the database, we can also use the getRepository function provided by TypeORM:

const user = await userRepository.findOne(1, { relations: ['address'] });
const address = await addressRepository.findOne(1, { relations: ['users'] });

The findOne method takes two arguments: the ID of the entity to find, and an options object. In this example, we also specify the relations option to eagerly load the related entities ('address' for the User entity and 'users' for the Address entity).

Updating Entities

To update an entity in the database, we can retrieve the entity, modify its properties, and then save it back to the database:

const user = await userRepository.findOne(1, { relations: ['address'] });
user.name = 'Jane Doe';

await userRepository.save(user);
Deleting Entities

To delete an entity from the database, we can use the remove method:

const user = await userRepository.findOne(1);
await userRepository.remove(user);
Conclusion

In this guide, we have shown how to perform CRUD operations with TypeORM relationships. TypeORM provides a powerful abstraction layer for working with databases and enables us to easily define and use relationships between entities.