entitycolumnotfound: столбец сущности «авторы» не найден. многие ко многим отношениям в TypeORM и NestJS

#sql #many-to-many #nestjs #typeorm

#sql #многие ко многим #nestjs #typeorm

Вопрос:

Я пытаюсь получить книги для каждого пользователя из запроса get У меня следующая проблема, оказывается, я использую отношение «многие ко многим», но это указывает на то, что объект authors не найден, я уже искал документацию TypeORM, но я ничего не могу найти, это мойкод:

book.controller.ts

 @Controller('book')
export class BookController {
    constructor(
        private readonly _bookService: BookService
    ) { }

    @Get('author/:authorId')
    getBooksByAuthor(
      @Param('authorId', ParseIntPipe) authorId: number,
    ): Promise<ReadBookDto[]> {
      return this._bookService.getBooksByAuthor(authorId);
    }

}
  

book.service.ts

     @Injectable()
    export class BookService {
        constructor(
            @InjectRepository(BookRepository)
            private readonly _bookRepository: BookRepository,
    
            @InjectRepository(UserRepository)
            private readonly _userRepository: UserRepository
        ) { }
    
        async getBooksByAuthor(authorId: number): Promise<ReadBookDto[]> {
    
            const books: Book[] = await this._bookRepository.find({

// This is where I have the entity of authors, it should be noted that the entity of books if I have it

                where: { status: status.ACTIVE, authors: In([authorId]) },
            })
            console.log(books)
            return books.map(book => plainToClass(ReadBookDto, book));
        }
    }
  

book.entity.ts

 import {
  BaseEntity,
  PrimaryGeneratedColumn,
  Column,
  ManyToMany,
  Entity,
  JoinColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';
import { User } from '../user/user.entity';

@Entity('books')
export class Book extends BaseEntity {
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ type: 'varchar', length: 100, nullable: false })
  name: string;

  @Column({ type: 'varchar', length: 500 })
  description: string;

  @ManyToMany(type => User, user => user.books, { eager: true, primary: true})
  @JoinColumn()
  authors: User[];

  @Column({ type: 'varchar', default: 'ACTIVE', length: 8 })
  status: string;

  @CreateDateColumn({ type: 'timestamp', name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'timestamp', name: 'updated_at' })
  updatedAt: Date;
}
  

Это пользовательская сущность, в которой я создаю отношение «многие ко многим
» user.entity.ts

 @Entity('users')
export class User extends BaseEntity {
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ type: 'varchar', unique: true, length: 25, nullable: false })
  username: string;

  @Column({ type: 'varchar', nullable: false })
  email: string;

  @Column({ type: 'varchar', nullable: false })
  password: string;

  @OneToOne(type => UserDetails, {
    cascade: true,
    nullable: false,
    eager: true,
  })
  @JoinColumn({ name: 'detail_id' })
  details: UserDetails;


  @ManyToMany(type => Book, book => book.authors)
  @JoinTable({ name: 'user_books' })
  books: Book[];

}
  

Если бы вы могли помочь мне найти ошибку, это было бы очень полезно
Спасибо

Ответ №1:

Вы можете использовать QueryBuilder для получения книг:

  @Injectable()
export class BookService {
    constructor(
        @InjectRepository(BookRepository)
        private readonly _bookRepository: BookRepository,

        @InjectRepository(UserRepository)
        private readonly _userRepository: UserRepository
    ) { }

    async getBooksByAuthor(authorId: number): Promise<ReadBookDto[]> {

       const books: Book[] = await this._bookRepository.createQueryBuilder('books')
                 .leftJoinAndSelect("books.authors", "users")
                 .where('books.status = :status',{status : status.ACTIVE})
                 .andWhere("users.id = :id ", { id: authorId })
                  .getMany();

        console.log(books)
        return books.map(book => plainToClass(ReadBookDto, book));
    }
}