英文:
Prisma filtering
问题
我必须根据以下条件使用 Prisma 应用筛选器。
如果 ShowActiveOnly 为 true,则仅显示处于活动状态的项目。
如果 showActiveOnly 为 false,则显示所有项目。
以下是我尝试过的代码片段。
export const getAllProducts = async (req: Request, res: Response) => {
try {
const page: number = Number(req.query.page) - 1 || 0;
const perPage: number = Number(req.query.perPage) || 10;
const showActiveOnly: boolean =
(req.query.showActiveOnly || "true") === "true";
const products = await _db.serviceProduct.findMany({
where: { IsActive: showActiveOnly },
skip: page * 10,
take: perPage,
});
res.json({ products, code: 200 }).status(200);
} catch (error) {
HandleError(error, res);
}
};
英文:
I've to apply filter using prisma as per the below condition.
if ShowActiveOnly is true, then only show which are active
if showActiveOnly is false, then show everything.
Below is the snippet I've tried.
export const getAllProducts = async (req: Request, res: Response) => {
try {
const page: number = Number(req.query.page) - 1 || 0;
const perPage: number = Number(req.query.perPage) || 10;
const showActiveOnly: boolean =
(req.query.showActiveOnly || "true") === "true";
const products = await _db.serviceProduct.findMany({
where: { IsActive: showActiveOnly },
skip: page * 10,
take: perPage,
});
res.json({ products, code: 200 }).status(200);
} catch (error) {
HandleError(error, res);
}
};
答案1
得分: 0
export const getAllProducts = async (req: Request, res: Response) => {
try {
const page: number = Number(req.params.page) - 1 || 0;
const perPage: number = Number(req.params.perPage) || 10;
const showActiveOnly: boolean =
(req.query.showActiveOnly || "true") === "true";
const products = await _db.serviceProduct.findMany({
where: showActiveOnly ? { IsActive: true } : undefined,
skip: page * perPage,
take: perPage,
});
res.json({ products, code: 200 }).status(200);
} catch (error) {
HandleError(error, res);
}
};
我们可以这样做。在数据提取的where
子句中应用了条件,如果showactiveonly
为true,则只获取isActive
为true的数据,否则where
子句为undefined。
英文:
export const getAllProducts = async (req: Request, res: Response) => {
try {
const page: number = Number(req.params.page) - 1 || 0;
const perPage: number = Number(req.params.perPage) || 10;
const showActiveOnly: boolean =
(req.query.showActiveOnly || "true") === "true";
const products = await _db.serviceProduct.findMany({
where: showActiveOnly ? { IsActive: true } : undefined,
skip: page * perPage,
take: perPage,
});
res.json({ products, code: 200 }).status(200);
} catch (error) {
HandleError(error, res);
}
};
we can do in this way. I've applied a condition in where clause in data extraction, if showactiveonly is true then we're getting only isActive true else where clause is undefined.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论