I have a simple ManyToMany setup with typeorm. According to the docs of typeORM on how to update/add a ManyToMany relation.
Link to the docs: https://typeorm.io/relational-query-builder
The query it produces, and here is the problem, it does not have 2 parameters and 'usersId' is empty. I think the user has to exist first before connecting them together, but maybe someone can confirm this? Why does it not create the user for me when adding a new user in enterprise?
query: SELECT "Enterprise"."id" AS "Enterprise_id", "Enterprise"."createdAt" AS "Enterprise_createdAt", "Enterprise"."updatedAt" AS "Enterprise_updatedAt", "Enterprise"."name" AS "Enterprise_name", "Enterprise"."erpCustomerCode" AS "Enterprise_erpCustomerCode", "Enterprise"."isActive" AS "Enterprise_isActive", "Enterprise"."street" AS "Enterprise_street", "Enterprise"."houseNumber" AS "Enterprise_houseNumber", "Enterprise"."city" AS "Enterprise_city", "Enterprise"."state" AS "Enterprise_state", "Enterprise"."country" AS "Enterprise_country", "Enterprise"."zip" AS "Enterprise_zip", "Enterprise"."geoLocation" AS "Enterprise_geoLocation", "Enterprise"."unitsSystem" AS "Enterprise_unitsSystem", "Enterprise"."weekNumberingSystem" AS "Enterprise_weekNumberingSystem", "Enterprise"."yearStart" AS "Enterprise_yearStart", "Enterprise"."weekStart" AS "Enterprise_weekStart" FROM "enterprises" "Enterprise" WHERE ("Enterprise"."id" = $1) LIMIT 1 -- PARAMETERS: ["d2f16db8-63be-4b09-a5ea-e04336069df4"]
User {}
query: INSERT INTO "enterprise_users"("enterprisesId", "usersId") VALUES ($1, DEFAULT) -- PARAMETERS: ["d2f16db8-63be-4b09-a5ea-e04336069df4"]
query failed: INSERT INTO "enterprise_users"("enterprisesId", "usersId") VALUES ($1, DEFAULT) -- PARAMETERS: ["d2f16db8-63be-4b09-a5ea-e04336069df4"]
I have the following setup:
enterprise.entity.ts
@Entity('enterprises')
export class Enterprise {
@PrimaryGeneratedColumn('uuid')
id: string;
@CreateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
@UpdateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
updatedAt: Date;
@Column({ unique: true, length: 50 })
name: string;
...
@ManyToMany(() => User, (users) => users.enterprises, { cascade: true })
@JoinTable({ name: 'enterprise_users' })
users: User[];
}
user.entity.ts
@Entity('users')
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@ManyToMany(() => Enterprise, (enterprise) => enterprise.users)
enterprises: Enterprise[];
}
enterprise.service.ts
@Injectable()
export class EnterpriseService {
constructor(
@InjectRepository(Enterprise)
private enterpriseRepository: Repository<Enterprise>,
) {}
async update(id: string, enterprise: UpdateEnterpriseDto) {
// for testing
const user = new User();
user.name = 'test123';
// triggers error
await this.enterpriseRepository.createQueryBuilder().relation(Enterprise, 'users').of(id).add(user);
return this.enterpriseRepository.save({ id, ...enterprise });
}
}
