Sequelize原始查询,使用绑定获取所有数据或特定数据(postgresql)

Sequelize raw query, get all data or specific data with bind (postgresql)

所以当我使用原始查询 select 时,我有产品 table 如果未指定集合,那么它将获取所有数据,但如果指定了集合,它将获取每个集合。这是我的代码:

  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 =  and cl.id = ) or (c.c_name = )
    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,
   });
  }
  };

我想实现的是:

  1. http://localhost:3001/api/v1/product/get?category=man 时,我将获取每个类别的所有数据 man, woman, or kid
  2. http://localhost:3001/api/v1/product/get?category=man&collection=1 时,我将获取每个类别的所有数据 man, woman or kid,但每个 id 1=topwear, 2=bottomwear 等的特定集合

当我执行上述操作时它真正做了什么:

  1. 只有在http://localhost:3001/api/v1/product/get?category=man
  2. 时才会得到message: {}
  3. http://localhost:3001/api/v1/product/get?category=man&collection=1
  4. 时获取所有数据,不关心集合

希望你能明白我的意思,能帮帮我....

我想你需要添加一个条件来检查传递的 collection 值:

 where (c.c_name =  and cl.id =  and  is not null) or (c.c_name =  and  is null)

当然,如果url中没有指定相应的查询参数,则需要在collection变量中传递null

P.S。在 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 },
   });