Search code examples
nestjstypeorm

How to Update a Nest Js Many To Many Relation


I have a Many to Many relationship between two entities. One is UserEntity and the other is FamilyEntity. In this project a user can belong to many families and a family can have many users.

Family Entity:

@Entity()
export class FamilyEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    familyName: string;

    @ManyToMany(() => UserEntity, user => user.families,{})
    public users: UserEntity[];


}

User Entity:

@Entity()
export class UserEntity {

    @PrimaryGeneratedColumn()
    public id?: number;

    @Column()
    public name: string;

    @Column({ unique: true })
    public username: string; 

    @Column({ unique: true })
    public password: string;

    @BeforeInsert()
    emailToLowerCase() {
        this.email = this.email.toLowerCase();
    }
    @Column({ unique: true })
    public email: string;

    @Column({ type: 'enum', enum: UserRole, default: UserRole.USER })
    public role: UserRole;

    @ManyToMany(() => FamilyEntity, family => family.users, {
        cascade: true,
        eager:true
    })
    @JoinTable()
    public families: FamilyEntity[];


}

I can save and update a user and family successfully with no problem but the relationship between the two entities is what is giving me a hard time. Say I want to update a user to include a family in fields I try the code :

 async updateFamily(id: number, user:User) {
        this.familyIds = user.families;
        user.families = [];

        for (let i = 0; i < this.familyIds.length; i++) {
            this.families = await this.familyRepository.findOne(this.familyIds[i]);
            user.families.push(this.families);
        }
        return from(this.userRepository.update(id, user.families));
        

    }

When I try and execute this ,I get an error: ER_BAD_FIELD_ERROR: Unknown column 'userEntityId' in 'field list'. I've searched the documentation and there is no reference on how to update a many to many relationship on both nest-js and type-orm. Kindly assist.


Solution

  • this.userRepository.update is supposed to have a UserEntity as the second argument.

    Instead of this.userRepository.update(id, user.families),

    Try:

    this.userRepository.update(id, user);
    

    or

    this.userRepository.save(user);
    

    Note that this will remove records from the join table if you didn't attach all the families in user.families