簡體   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