【发布时间】:2021-12-13 21:16:58
【问题描述】:
所以当我使用原始查询选择时我有产品表,如果未指定集合,那么它将获取所有数据,但如果指定了集合,它将获取每个集合。这是我的代码:
const { category, collection } = req.query;
const sql = `
select
p.id,
p.p_image,
p.p_name,
p.p_desc,
p.p_prize,
p.p_stock,
c.c_name,
cl.cl_name
from products as p
inner join collections as cl on cl.id = p.p_collection_id
inner join categories as c on c.id = cl.cl_category_id
where (c.c_name = $1 and cl.id = $2) or (c.c_name = $1)
order by p."createdAt" desc; `;
try {
const getData = await Product.sequelize.query(sql, {
bind: [category, collection],
});
if (getData[0] != "") {
res.status(200).send({
s: 1,
message: "success retrive all products",
data: getData[0],
});
} else {
res.status(404).send({
s: 0,
message: "data not found",
});
}
} catch (err) {
res.status(500).send({
message: err,
});
}
};
我想要实现的是:
- 当
http://localhost:3001/api/v1/product/get?category=man时,我将获得每个类别的所有数据man, woman, or kid - 当
http://localhost:3001/api/v1/product/get?category=man&collection=1时,我将获取每个类别的所有数据man, woman or kid,但每个ID 的特定集合1=topwear, 2=bottomwear等。
当我在上面做的时候它真的做了什么:
- 只有在
http://localhost:3001/api/v1/product/get?category=man时才会得到message: {} -
http://localhost:3001/api/v1/product/get?category=man&collection=1时获取所有数据,不关心集合
我希望你能理解我的意思并能帮助我......
【问题讨论】:
标签: node.js postgresql express sequelize.js