question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

'WHERE' of the join query is generated "wrong"

See original GitHub issue

Hello guys, I did a test using ManyToOne but I get the following error:

error: error: invalid reference to FROM-clause entry for table "comment"

The error occurs when I run the following route

GET http://localhost:3000/post/1/comment

Looking at the log, I saw the following QUERY:

SELECT "Comment"."id" AS "Comment_id", "Comment"."text" AS "Comment_text", "post"."id" AS "post_id", "post"."body" AS "post_body", "post"."commentsId" FROM "comment" "Comment" LEFT JOIN "post" "post" ON "post"."commentsId"="Comment"."id" WHERE (Comment.postId = $1)

And doing tests directly in the database and works with this SQL (I added the quotes on WHERE it)

SELECT "Comment"."id" AS "Comment_id", "Comment"."text" AS "Comment_text", "post"."id" AS "post_id", "post"."body" AS "post_body", "post"."commentsId" FROM "comment" "Comment" LEFT JOIN "post" "post" ON "post"."commentsId"="Comment"."id" WHERE ("Comment"."postId" = $1)

It is probably some wrong setting I made. I did some tests and research, both in TypeORM, and directly in the PG plugin but I was not successful.

follows some useful files

dependencies in package.json

  "dependencies": {
    "@nestjs/common": "^6.7.2",
    "@nestjs/core": "^6.7.2",
    "@nestjs/platform-express": "^6.7.2",
    "@nestjs/typeorm": "^6.2.0",
    "@nestjsx/crud": "^4.4.1",
    "@nestjsx/crud-typeorm": "^4.4.1",
    "class-transformer": "^0.2.3",
    "class-validator": "^0.11.0",
    "pg": "^7.17.1",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.0",
    "rxjs": "^6.5.3",
    "typeorm": "^0.2.22"
  },

Main Module

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostModule } from './post/post.module';
import { CommentModule } from './comment/comment.module';
import { Comment } from './comment/comment.entity';
import { Post } from './post/post.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'postgres',
      database: 'test',
      logging: true,
      entities: [
        Post, Comment
      ],
      synchronize: true,
    }),
    PostModule,
    CommentModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Entities

Post

import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm";
import { Comment } from '../comment/comment.entity';

@Entity()
export class Post {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    body: string

    @ManyToOne(type => Comment, c => c.post)
    comments: Post[]
}

Comment

import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
import { Post } from '../post/post.entity';


@Entity()
export class Comment {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    text: string

    @OneToMany(type => Post, p => p.comments)
    post: Post
}

Modules

Post

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";

import { Comment } from "./comment.entity";
import { CommentService } from "./comment.service";
import { CommentController } from "./comment.controller";

@Module({
  imports: [TypeOrmModule.forFeature([Comment])],
  providers: [CommentService],
  exports: [CommentService],
  controllers: [CommentController]
})
export class CommentModule {}

Comment

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";

import { Post } from "./post.entity";
import { PostService } from "./post.service";
import { PostController } from "./post.controller";

@Module({
  imports: [TypeOrmModule.forFeature([Post])],
  providers: [PostService],
  exports: [PostService],
  controllers: [PostController]
})
export class PostModule {}

Services

Post

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { TypeOrmCrudService } from "@nestjsx/crud-typeorm";

import { Comment } from "./comment.entity";

@Injectable()
export class CommentService extends TypeOrmCrudService<Comment> {
  constructor(@InjectRepository(Comment) repo) {
    super(repo);
  }
}

Comment

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { TypeOrmCrudService } from "@nestjsx/crud-typeorm";

import { Comment } from "./comment.entity";

@Injectable()
export class CommentService extends TypeOrmCrudService<Comment> {
  constructor(@InjectRepository(Comment) repo) {
    super(repo);
  }
}

Controller

Post

import { Controller } from "@nestjs/common";
import { Crud, CrudController } from "@nestjsx/crud";

import { Comment } from "./comment.entity";
import { CommentService } from "./comment.service";

@Crud({
  model: {
    type: Comment
  },
  params: {
    id: {
        field: 'id',
        type: 'number',
        primary: true,
    },
      postId: {
          field: 'postId',
          type: 'number'
      },
    
  },
  query: {
    join: {
        post: {
            eager: true
        }
    }
  }
})
@Controller("post/:postId/comment")
export class CommentController implements CrudController<Comment> {
  constructor(public service: CommentService) {}
}

Comment

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

What am I doing wrong? I already appreciate the help 😄

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:3
  • Comments:30 (10 by maintainers)

github_iconTop GitHub Comments

4reactions
idhardcommented, May 11, 2020

hey sorry to comment in a closed ticket, i just updated nextjs crud and i’m having same issue in postgresql when filtering results in CrudAuth by a related column for example :

@CrudAuth({
  property: 'user',
  filter: (user: UserEntity): SCondition => {
    const { account } = user;
    const sCondition = [];
    sCondition.push({ createdBy: { $eq: account.id } });
    return {
      $or: sCondition,
    };
  },
})

generates this error

QueryFailedError: column Customer.createdById.id does not exist

But if i use

@CrudAuth({
  property: 'user',
  filter: (user: UserEntity): SCondition => {
    const { account } = user;
    const sCondition = [];
    sCondition.push({ 'Customer.createdBy': { $eq: account.id } });
    return {
      $or: sCondition,
    };
  },
})

works!

thanks

3reactions
michaelyalicommented, Apr 25, 2020

I’ll publish it today. Sorry for the delay

Read more comments on GitHub >

github_iconTop Results From Across the Web

Hibernate generates wrong inner join query for MySQL
TypedQuery<KundeDTO> query = entityManager.createQuery("select new zdb.dto.KundeDTO(k.id, k.firma.firmenname, k.regnr, k.kategorie) ...
Read more >
MySQL JOIN query produces wrong result
The problem is the subquery, where you combine in the select list both an aggregated ( max(cr.posted_dt) ) and non-aggregated expressions/columns from the ......
Read more >
A self-join query in combination with BY clause generates an ...
A self-join query with a BY clause generates a SQL query with an ORDER BY clause with the wrong index. URL Name.
Read more >
Query Engine Error 'If tables are already linked then the join ...
The errors indicate that the report contains cyclical joins that are resulting in an illegal query. A report that contains a cyclical join...
Read more >
Database Engine events and errors - SQL Server
Consult this MSSQL error code list to find explanations for error ... 1016, 15, No, Outer join operators cannot be specified in a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found