TypeORM: Joining when we have one to many and many to one relationship

I have been struggling with the same problem myself.

You should change the relation here:

@OneToMany(type => Image, image => image.id)
images: Image[];

To this:

@OneToMany(type => Image, image => image.post)
images: Image[];

Notice that image.id should be image.post instead to match the inverse side.

*Edit => Over here the same problem appears:

@OneToMany(type => Post, post => post.id)
posts: Post[];

This relation should also have the inverse side, post.id should be post.user instead:

@OneToMany(type => Post, post => post.user)
posts: Post[];

Be careful about this since it doesn't throw any errors until runtime.

I just tested this query with the above modifications and the error is gone:

return await this.postRepository.find({
  relations: ['images', 'user'],
  where: { user: { id: id } },
});

You may also omit the @JoinColumn() decorators, as they are not necessary in one to many and many to one relationships, you can see it mentioned in the official docs:

You can omit @JoinColumn in a @ManyToOne / @OneToMany relation. @OneToMany cannot exist without @ManyToOne. If you want to use @OneToMany, @ManyToOne is required. Where you set @ManyToOne - its related entity will have "relation id" and foreign key.

Refer to the TypeORM documentation for more details about this, you will also find an example of this type of relation.


@Entity()
export class User {

 @OneToMany(type => Post, post => post.user)
 posts: Post[];
}

@Entity()
export class Post {

 @PrimaryGeneratedColumn()
 id: number;

 @Column()
 user_id: number;

 @ManyToOne(type => User)
 @JoinColumn({name: 'user_id', referencedColumnName: 'id'})
 user: User;

 @OneToMany(type => Image, image => image.post)
 images: Image[];
}

@Entity()
export class Image {
 @PrimaryGeneratedColumn()
 id: number;

 @Column()
 post_id: number;

 @ManyToOne(type => Post)
 @JoinColumn({name : 'post_id', referencedColumnName: 'id'})
 post: Post;
}

Try this

Tags:

Typeorm

Nestjs