请教老师关于QueryBuilder的建议
来源:8-11 高级查询:使用QueryBuilder进行联合查询

LinkeZ
2023-07-11
async findOneByIdWithPage(query: GetMenuById) {
const { id, limit, page } = query;
const skip = (page - 1) * limit;
const menuTem = await this.menuRepository.findOne({
where: { id, isDelete: false },
relations: ['image', 'motto'],
});
if (id === 1 || menuTem.menuName === '主页') {
return {
...menuTem,
blog: await this.blogRepository.find({
where: { published: true },
order: { id: 'DESC' },
skip,
take: limit,
}),
};
} else {
return this.menuRepository
.createQueryBuilder('menu')
.where('menu.id = :id', { id })
.leftJoinAndSelect('menu.image', 'image')
.leftJoinAndSelect('menu.motto', 'motto')
.leftJoinAndSelect('menu.blog', 'blog')
.orderBy('blog.id', 'DESC')
.getOne();
}
}
请教老师,如上面的代码if
块中在Blog中没有与Menu的id为1或Menu的menuName为"主页"相关联的数据,但是需要查询所有Blog的数据按分页条件进行返回。
像这种情况有方法只写一段QueryBuilder就可以完成吗?或老师有任何建议吗?
非常感谢!
写回答
1回答
-
async findOneByIdWithPage(query: GetMenuById) { const { id, limit, page } = query; const skip = (page - 1) * limit; const menuTem = await this.menuRepository.findOne({ where: { id, isDelete: false }, relations: ['image', 'motto'], }); const blogs = await this.blogRepository.find({ where: { published: true }, order: { id: 'DESC' }, skip, take: limit, }); if (id === 1 || menuTem.menuName === '主页') { return { ...menuTem, blog: blogs, }; } else { //如果不需要返回所有的已发布的博客,可以注释或删除以下代码 return { ...menuTem, blog: blogs, }; // 如果需要返回 menu 和它的关联博客,可以取消以下代码的注释 /* return this.menuRepository .createQueryBuilder('menu') .where('menu.id = :id', { id }) .leftJoinAndSelect('menu.image', 'image') .leftJoinAndSelect('menu.motto', 'motto') .leftJoinAndSelect('menu.blog', 'blog') .orderBy('blog.id', 'DESC') .getOne(); */ } }
试试?
022023-08-16
相似问题