0

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?

1 Answer 1

1

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;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sure, thanks to accepting this answer if it resolves your problem
could you take a look please stackoverflow.com/questions/66210852/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.