Hi,
I have two entities that have a many to many relations between them, when I do role.users.add(user) (with users initialized) the collection is updated, but after that, if I interact with the role or user entity it seems that MikroORM is trying to perform an update request against the users table with invalid data (trying to set the email field to NULL while it is non-nullable)
// Controller
export class RolesController {
constructor(private readonly rolesService: RolesService) {}
@Post(':role_id/users/:user_id')
async addUserToRole(@Param('role_id') role_id: number, @Param('user_id') user_id: number) {
return this.rolesService.addUser(role_id, user_id);
}
}
// Service
export class RolesService {
constructor(private readonly orm: MikroORM) {}
@UseRequestContext()
async addUser(role_id: number, user_id: number): Promise<BaseUserResponseDTO[]> {
const role = await this.orm.em.findOne(Role, { id: role_id });
if (!role) throw new NotFoundException(`Role with ID ${role_id} not found`);
const user = await this.orm.em.findOne(User, { id: user_id });
if (!user) throw new NotFoundException(`User with ID ${user_id} not found`);
await role.users.init();
role.users.add(user);
await this.orm.em.persistAndFlush(role);
const res: BaseUserResponseDTO[] = [];
role.users.getItems().forEach((user) =>
res.push({
id: user.id,
updated_at: user.updated_at,
created_at: user.created_at,
first_name: user.first_name,
last_name: user.last_name,
nickname: user.nickname,
}),
);
return res;
}
}
@Entity({ tableName: 'users' })
export class User {
// ...
@Property({ unique: true })
email: string;
/** Linked roles to the user */
@ManyToMany(() => Role, (role) => role.users)
roles = new Collection<Role>(this);
}
@Entity({ tableName: 'roles' })
export class Role {
// ...
/** Specify to which user the role is attached */
@ManyToMany(() => User, (user) => user.roles, { owner: true })
users = new Collection<User>(this);
}
