Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alias was not found. Maybe you forget to join it

In my nectjs project I'm using TypeORM and I have 2 entities user and post, and I'm tying to make a relation between them

user.entity.ts

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

  @Column({ length: 50, unique: true })
  name: string;

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

post.entity.ts

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

  @Column({ length: 30 })
  title: string;

  @ManyToOne(type => User, user => user.posts)
  user: User;
}

So I want to join these tables and get post by it's title for specific user

const PostObject = await createQueryBuilder("post")
      .leftJoinAndSelect(
        "post.user",
        "user",
        "post.title = :title",
        { title: "title1" }
      )
      .where("user.id = :id", { id: id })
      .getOne();

but when I run the project and execute this function I get this error:

Error: "post" alias was not found. Maybe you forget to join it?
like image 448
muklah Avatar asked Feb 13 '19 11:02

muklah


1 Answers

You have to inject the Repository first:

constructor(
  @InjectRepository(Post) private readonly postRepository: Repository<Post>
) {
}

Then you can create the QueryBuilder for the Post entity by passing in the alias:

this.postRepository.createQueryBuilder('post')
// ^^^^^^^^^^^^^^^^
   .leftJoinAndSelect(
     'post.user',
     'user',
     'post.title = :title',
     { title: 'title1' },
   )
   .where('user.id = :id', { id })
   .getOne();
like image 154
Kim Kern Avatar answered Oct 21 '22 03:10

Kim Kern