Check => https://gist.github.com/nicobytes/7fb83f8feab37ef7b31923cdeb4e20c8 https://app.quickdatabasediagrams.com/#/
// src/tasks/entities/user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User{
@PrimaryGeneratedColumn()
id: number;
@Column()
email: string;
@Column()
password: string;
}
// src/tasks/entities/profile.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from 'typeorm';
import { User } from './user.entity';
@Entity()
export class Profile {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ name: 'last_name' })
lastName: string;
}
// src/tasks/task.module.ts
@Module({
imports: [TypeOrmModule.forFeature([Task, User, Profile])],
providers: [TasksService, UserService],
controllers: [TasksController, UserController],
})
export class TasksModule {}
// src/tasks/entities/user.entity.ts
@OneToOne(() => Profile)
@JoinColumn({ name: 'profile_id' })
profile: Profile;
// src/tasks/entities/profile.entity.ts
@OneToOne(() => User, (user) => user.profile)
user: User;
npm run migrations:generate -- new-tables
npm run migrations:run
// nest g service tasks/services/user --flat
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './../entities/user.entity';
import { Profile } from './../entities/profile.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User) private userRepo: Repository<User>,
@InjectRepository(Profile) private profileRepo: Repository<Profile>,
) {}
findAll() {
return this.userRepo.find({
relations: ['profile'],
});
}
async create(body: any) {
const profile = new Profile();
profile.name = body.name;
profile.lastName = body.lastName;
const newProfile = await this.profileRepo.save(profile);
const user = new User();
user.email = body.email;
user.password = body.password;
user.profile = newProfile;
return this.userRepo.save(user);
}
}
// nest g co tasks/controllers/user --flat
import { Controller, Get, Post, Body } from '@nestjs/common';
import { UserService } from './../services/user.service';
@Controller('api/users')
export class UserController {
constructor(private userService: UserService) {}
@Get()
findAll() {
return this.userService.findAll();
}
@Post()
create(@Body() body: any) {
return this.userService.create(body);
}
}