How to insert using TypeORM's createQueryBuilder with many-to-many relation

Viewed 30

I want to insert a new row in a table (user) with a many-to-many relation to an other table (tag). The user does not exist prior to this operation. The tag must be inserted only if not present in the tag table. The relation table is always populated as a user must have at least one tag.

The User entity has a primary generated column id, some columns, and this many-to-many relation:

@ManyToMany(
    type => Tag, 
    tag => tag.users, 
    { cascade: true }
)
@JoinTable(
    { name: "user_tags" }
)
tags!: Tag[]

The Tag entity has a primary generated column id, a name column, and a similar many-to-many relation to Users entity like the one above. The tables are created and the relation table is also there.

+---------+---------+-------------------------+
|                  user_tags                  |
+---------+---------+-------------------------+
| userId  | int(11) | PRIMARY KEY FOREIGN KEY |
| tagId   | int(11) | PRIMARY KEY FOREIGN KEY |
+---------+---------+-------------------------+

I want to use createQueryBuilder like the docs suggests:

await dataSource
    .createQueryBuilder()
    .relation(Post, "categories")
    .of(post)
    .add(category)

The problem is that I don't know what post or category refers to.

Source says .of()

Sets entity (target) which relations will be updated.

And that .add()

Adds (binds) given value to entity relation. Value can be entity, entity id or entity id map (if entity has composite ids). Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). Works only for many-to-many and one-to-many relations. For many-to-one and one-to-one use #set method instead.

Can someone explain this to me as I don't understand how to use it? Also maybe a commented code example of the whole process?

Thank you.

0 Answers
Related