在写代码的时候发现在查询数据时通过relation获取的关联关系entity中的数据无法正常拦截,代码如下:
blog.controller.ts
@Get()
@UseInterceptors(new SerializeInterceptor(GetAllBlogDto))
findAll() {
return this.blogService.findAll();
}
blog.Service.ts
...
async findAll() {
return await this.blogRepository.find({
where: { isDelete: false, published: true },
relations: ['image'],
});
}
GetAllBlogDto.ts
import { Expose } from 'class-transformer';
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
import { Image } from '../../image/entities/image.entity';
class ImageDto extends Image {
@IsString()
@IsNotEmpty()
@Expose()
url: string;
}
export class GetAllBlogDto {
@IsNumber()
@IsNotEmpty()
@Expose()
id: number;
@IsString()
@IsNotEmpty()
@Expose()
blogTitle: string;
@IsString()
@IsNotEmpty()
@Expose()
summary: string;
@IsString()
@IsNotEmpty()
@Expose()
image: ImageDto;
}
通过上面代码想要获取这样的数据:
[
{
id:1,
blogTitle: **,
summary:**,
image: {
url: **,
}
},
{....}
]
但获取到的数据中image
一直为空对象,除了在image的entity中添加@Expose()
外,请问老师还有没有其它办法?
非常感谢!