1

For example

@Entity()
class Post {

  @Column()
  post_hash: string;

  @Column()
  title: string;

  categorys:  Array<Category> = []; 
}

@Entity()
class Category {

  @Column()
  content: string;

  @Column()
  post_hash: number;

}

I want to query all the category content of the corresponding post through Typeorm.

I tried this method and failed.

this.createQueryBuilder('Post').leftJoinAndMapOne(
            'Post.categorys',
             Category,
            'category',
            'category.post_hash = post.post_hash'
      )

This is my error message. QueryFailedError: relation "post" does not exist

99kies
  • 173
  • 1
  • 8

1 Answers1

1

Entities

First of all, you must identify each row with a unique ID using @PrimaryColumn() or @PrimaryGeneratedColumn() decorators.

Each Post entity can have multiple categories and each Category entity is related to multiple posts. This is called a many-to-many relation and must be correctly mapped using the @ManyToMany() decorator. See this for more information.

@Entity()
class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  post_hash: string;

  @Column()
  title: string;

  @ManyToMany(() => Category, category => category.posts)
  @JoinTable()
  categories: Category[];
}
@Entity()
class Category {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  content: string;

  @Column()
  post_hash: number;

  @ManyToMany(() => Post, post => post.categories)
  posts: Post[];
}

Query

Obtain all Post(s) with the related categories.

Using find:

const posts: Post[] = await getRepository(Post)
                             .find({ relations: ['categories'] });

Using QueryBuilder:

const posts: Post[] = await getRepository(Post)
                             .createQueryBuilder('post')
                             .leftJoinAndSelect('post.categories', 'category')
                             .getMany();
Carlo Corradini
  • 2,927
  • 2
  • 18
  • 24
  • Thank you very much! But I still want to ask about the way to write one-to-many relationships (post->Categories), post and category are just a few examples I've provided – 99kies Aug 04 '21 at 04:03
  • If you want multiple posts to have multiple categories and vice versa multiple categories to be mapped to multiple posts you must use N-to-N relation. If you want an array where each element is a foreign key this is not possible -> see [this](https://stackoverflow.com/questions/41054507/postgresql-array-of-elements-that-each-are-a-foreign-key). – Carlo Corradini Aug 04 '21 at 18:09