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

编程入门 行业动态 更新时间:2024-10-08 08:22:23

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用使用存储库和一对多关系插入数据?"/>

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

我有两个实体,产品和类别我曾尝试将数据添加到数据库,但没有收到错误消息。但是结果不是我的期望。结果成功,但是当我转到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;
}

更多推荐

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

本文发布于:2024-05-07 07:24:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   关系   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!