最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何使用使用存储库和一对多关系插入数据?

IT培训 admin 13浏览 0评论

如何使用使用存储库和一对多关系插入数据?

我有两个实体,产品和类别我曾尝试将数据添加到数据库,但没有收到错误消息。但是结果不是我的期望。结果成功,但是当我转到mysql并查看相关表时,categoryId字段似乎被标记为null

我的产品实体

export class Product {

  @PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
  id: number;

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

  @Column({ type: 'int' })
  price: number;

  @Column({ type: 'varchar', length: 255 })
  code: string;

  @Column({ type: 'timestamp', nullable: true })
  created_at: Date;

  @ManyToOne(type => Category, category => category.products,
    { cascade: ['insert', 'update'],eager:true,onDelete:"CASCADE",onUpdate:"CASCADE" })
  category: Category;
}

我的产品服务

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private productRepository: Repository<Product>,
  ) {
  }




  create(createProductDto: ProductDto): Promise<Product> {
    const product = new ProductDto();
    product.categoryId =createProductDto.categoryId;
    product.code=createProductDto.code;
    product.name = createProductDto.name;
    product.price = createProductDto.price;
    return  this.productRepository.save(product)
  }


}
回答如下:

您需要将categoryId外键添加到Product实体:

export class Product {
  //...
  @Column()
  categoryId: number;
}

如何使用使用存储库和一对多关系插入数据?

我有两个实体,产品和类别我曾尝试将数据添加到数据库,但没有收到错误消息。但是结果不是我的期望。结果成功,但是当我转到mysql并查看相关表时,categoryId字段似乎被标记为null

我的产品实体

export class Product {

  @PrimaryGeneratedColumn({ type: 'bigint', unsigned: true })
  id: number;

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

  @Column({ type: 'int' })
  price: number;

  @Column({ type: 'varchar', length: 255 })
  code: string;

  @Column({ type: 'timestamp', nullable: true })
  created_at: Date;

  @ManyToOne(type => Category, category => category.products,
    { cascade: ['insert', 'update'],eager:true,onDelete:"CASCADE",onUpdate:"CASCADE" })
  category: Category;
}

我的产品服务

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private productRepository: Repository<Product>,
  ) {
  }




  create(createProductDto: ProductDto): Promise<Product> {
    const product = new ProductDto();
    product.categoryId =createProductDto.categoryId;
    product.code=createProductDto.code;
    product.name = createProductDto.name;
    product.price = createProductDto.price;
    return  this.productRepository.save(product)
  }


}
回答如下:

您需要将categoryId外键添加到Product实体:

export class Product {
  //...
  @Column()
  categoryId: number;
}
发布评论

评论列表 (0)

  1. 暂无评论