簡體   English   中英

不使用 nodejs 進行嚴格搜索

[英]No strict search using nodejs

我在數據庫中有這些數據,我希望如果用戶搜索“ja”,結果將同時顯示“james”和“jam”

  async getUsername(searchname){
    let result = await Database.getConnection().models.User.findAll({ 
      where: { 
        FirstName: searchname
      },
      raw: true
    });
    
    return result;
  },

數據

{
  Firstname: "james",
  ....,
},
{
  Firstname: "jam",
  ....,
},
{
  Firstname: "Harltan",
  ....,
},
{
  Firstname: "Hames",
  ....,
}

當前結果是我鍵入或搜索 ja,沒有找到結果,但如果我搜索 jam,則會顯示“jam”數據

我使用的數據庫是 mysql

假設您使用的是Sequelize ,您可以簡單地使用startsWith運算符

const { Op } = require("sequelize");

// ...

let result = await Database.getConnection().models.User.findAll({ 
  where: { 
    FirstName: {
      [Op.startsWith]: searchname
    },
  },
  raw: true,
});

有關詳細信息,請參閱操作員文檔。

Sequelize v6 中可用的搜索運算符范圍是

      [Op.like]: '%hat',                       // LIKE '%hat'
      [Op.notLike]: '%hat',                    // NOT LIKE '%hat'
      [Op.startsWith]: 'hat',                  // LIKE 'hat%'
      [Op.endsWith]: 'hat',                    // LIKE '%hat'
      [Op.substring]: 'hat',                   // LIKE '%hat%'
      [Op.iLike]: '%hat',                      // ILIKE '%hat' (case insensitive) (PG only)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (PG only)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (PG only)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (PG only)

以您的搜索開頭的字符串搜索作為您的示例

const { Op } = require("sequelize")

let result = await Database.getConnection().models.User.findAll({ 
  where: { 
    FirstName: {
      [Op.startsWith]: searchname,
    }
  },
  raw: true
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM