【发布时间】:2021-02-22 00:47:11
【问题描述】:
我正在尝试从获取请求中获取每个用户的书籍 我有以下问题,原来我正在做一个多对多的关系,但它表明作者实体没有找到,我已经搜索了 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[];
}
如果您能帮我找出错误,那将非常有帮助 谢谢
【问题讨论】:
标签: sql many-to-many nestjs typeorm