nestjs+typeOrm 一对一关系,关联表数据删不掉?

作者站长头像
站长
· 阅读数 8

现在有一个user表,和 profile表,userprofile是一对一关系;添加正常,user 和 profile表都会有数据;问题是 删除不正常,user表可以正常删除,profile删不掉我看文的说是得加上关联关系,我这里都加上了,一直不好使,崩溃呃了

entity如下:

user entity

import { Profile } from './profile.entity';
import { Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ type: 'varchar' })
    name: string;

    @OneToOne(() => Profile, (profile) => profile.user, {
        cascade: true,
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE',
    })
    @JoinColumn()
    profile: Profile;
}

profile entity

import { User } from './user.entity';
import { Column, Entity, OneToOne, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Profile {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    gender: string;

    @OneToOne(() => User, (user) => user.profile)
    user: User;
}

user dto

import { Profile } from '../entities/profile.entity';

export class CreateUserDto {
    name: string;

    profile: Profile;
}

user controller

import { Controller, Post, Body, Param, Delete } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';

@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) {}

    @Post()
    create(@Body() createUserDto: CreateUserDto) {
        return this.userService.create(createUserDto);
    }

    @Delete(':id')
    remove(@Param('id') id: string) {
        return this.userService.remove(+id);
    }
}

user service

import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {
    @InjectRepository(User)
    user: Repository<User>;

    // 创建是正常的,user 和 profile表都会有数据
    create(createUserDto: CreateUserDto) {
        const user = new User();
        user.name = createUserDto.name;

        user.profile = createUserDto.profile;
        return this.user.save(user);
    }

    // 问题出现在这里,只删除了user表的数据,profile表的数据没有删除掉
    // 希望profile表的数据也能删除掉
    async remove(id: number) {
        const user = await this.user.findOne({
            where: { id },
            relations: ['profile'],
        });
        console.log(user);
        if (!user) {
            throw new NotFoundException();
        }
        return this.user.remove(user);
    }
}
回复
1个回答
avatar
test
2024-06-29

经过分析与实际操作,问题出现在实体逻辑错误!正确的方案:吧一对一的关系放在profile里面就好了

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容