2

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

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.