所以當我選擇原始查詢時我有產品表,如果未指定集合,則它將獲取所有資料,但如果指定了集合,它將獲取每個集合。這是我的代碼:
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等。
當我執行上述操作時,它真正做了什么:
- 只有
message: {}當http://localhost:3001/api/v1/product/get?category=man - 它獲取所有資料并且不關心收集時
http://localhost:3001/api/v1/product/get?category=man&collection=1
我希望你能理解我的意思,并能幫助我請......
uj5u.com熱心網友回復:
我想你需要添加一個條件來檢查傳遞的collection值:
where (c.c_name = $1 and cl.id = $2 and $2 is not null) or (c.c_name = $1 and $2 is null)
當然null,collection如果url中沒有指定相應的查詢引數,則需要傳入變數。
PS 在bind選項和 SQL 查詢本身中使用命名引數更好、更易讀,如下所示:
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 = $category and cl.id = $collection and $collection is not null)
or (c.c_name = $category and $collection is null)
order by p."createdAt" desc; `;
try {
const getData = await Product.sequelize.query(sql, {
bind: { category, collection },
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343622.html
標籤:节点.js PostgreSQL 表达 sequelize.js
