简体   繁体   中英

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

I have two entities Product and Category I had tried to add data to database but I'm not get error. But the result is not my expect. the result is successful but when I go to mysql and look at the related table, the categoryId field appears to be marked as null

My Product Entitiy

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;
}

My Product Service

@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)
  }


}

You need to add categoryId foreign key to your Product entity:

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

It automatically update categoryId foreign key in Product Table by assigning category object to product.category.

I am just adding an example from my scenario....

<!--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"
    }
}

Then It should automatically updated userTypeId in database, there is no need to add separate field for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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