繁体   English   中英

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

[英]How to insert data with use repository and relation one-to-many?

我有两个实体产品和类别我曾尝试将数据添加到数据库,但我没有收到错误。 但结果出乎我的意料。 结果是成功的,但是当我从 go 到 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;
}

它通过将类别 object 分配给 product.category 来自动更新Product Table中的categoryId外键。

我只是从我的场景中添加一个例子......

<!--User Entity with Many to One relation to User Type>
@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({length: 50})
  firstName: string;

  @Column({length: 50})
  lastName: string;

  @Column({length: 50})
  address: string;

  @Column({length: 50})
  street: string;

  @Column({length: 10})
  phoneNumber: string;

  @Column({length: 50})
  email: string;

  @ManyToOne(() => UserType)
  @JoinColumn()
  userType: UserType;

  @Column({ default: false })
  isVerified: number;
}

<!-Uset Type Entity->
@Entity()
export class UserType extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    description: string;
}



<!--My post data to insert-->
{
    "firstName": "Hashir",
    "lastName": "Muhammed",
    "address1": "Pulasseri House",
    "address2": "",
    "street": "Pazhaya Lakkidi",
    "phoneNumber": "9539191411",
    "email": "hussainmohd.p@gmail.com",
    "userType": {
        "id": 1,
        "name": "Admin",
        "description": "Admin will have all privileges to add and update application data"
    }
}

然后它应该自动更新数据库中的 userTypeId,不需要为此添加单独的字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM