Asking
Asking

Reputation: 4192

Add new data in database using TypeOrm

I am using in my NestJs application type-orm. I have 2 entities:

  1. User

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  gender: string;

  @OneToMany(() => Address, (address) => address.user)
  address: Address;
}

  1. Address

@Entity()
export class Address {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => User, (user) => user.address)
  user: User;
}

The idea is next: Each user can have multiple addresses, this is why i used OneToMany.

My provider looks like this:

async add(): Promise < User > {
  try {
    const newPost = this.usersRepository.create({
      gender: 'm',
    });
    return await this.usersRepository.save(newPost);
  } catch (err) {
    return err;
  }
}

It works and in db, in the table user i can add gender: 'm'.
Issue: How to add in add() function and the addresses, because now i can add just the user.
Question: How to change the add() function to be able to add and addresses?

Upvotes: 0

Views: 4144

Answers (1)

Ayoub Touba
Ayoub Touba

Reputation: 2987

First of all, you have to fix the User entity by making addresses as an Array of addresses,

    @Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  gender: string;

  @OneToMany(() => Address, (address) => address.user)
  address: Address[];
}

For your question, you can achieve adding the address by saving them first then bind them with the user:

   async add(): Promise < User > {
  try {
    let adresses:Array<Address> = [] ; array of type Address entity
 for(let adress of sourceOfyouAdressses) //sourceOfyouAdressses = the array of addresses you want add
   {
    let  adrs =  await this.adress Repository.save({city: adress.city }); // here you save you adress informations
    adresses.push(adrs ); 
   }
const newPost = this.usersRepository.create({
      gender: 'm',
      address:adresses
    });
    return await this.usersRepository.save(newPost);
  } catch (err) {
    return err;
  }
}

Upvotes: 1

Related Questions