如何使用sequelize为从数据库中获取的结果分配权重?

时间:2019-01-11 11:54:27

标签: javascript sql-server sails.js sequelize.js

基于字符串匹配模式,我正在将字符串与表的多个列进行比较,我想为行分配权重,这样  如果搜索条目与某个模式的列匹配,则会返回一个数字,该数字将添加到下一次后续案例检查的结果返回中,因此我们计算一行的权重。此查询产生所需的结果,我怎么想用sequalize做到。我不知道如何用续集计算权重,到目前为止,我已经做了类似的事情。

SELECT *,
CASE WHEN GivenName LIKE 'ahm%'  THEN 20 else  CASe  WHEN 
GivenName LIKE '%ahm%' then  10 else 0 end end
  + CASE  WHEn FamilyName LIKE '%ahm%' then  5 else  0 END
  + CASE when Email   LIKE '%ahm%' then  1 else  0 End
AS weight
FROM PersonAuth
WHERE (
 GivenName LIKE '%Ahm%'
OR FamilyName LIKE '%Ahm%'
OR Email         LIKE '%Ahm%'
)
ORDER BY weight DESC;

现在我想用sequelize编写相同的查询,以便将一个条件检查的权重添加到下一个条件结果。

 let agents =  (await PersonAuth.findAll({
       include: [
       {
         model: QueueButton,
         association: 'Buttons'
       },
       {
         model: Role
        }
     ],
       attributes: [
        'GivenName',
        'FamilyName',
        [sequalize.literal(`CASE WHEN GivenName LIKE 
       '${inputs.Name}%' THEN 20 else CASE WHEN GivenName LIKE 
      '%ahm%' THEN 10 else 0 end  end`), 'weight'],
       [sequalize.literal(`CASE WHEN FamilyName LIKE 
     '%${inputs.Name}%' THEN 5 else 0 end`),'wait'],
      [sequalize.literal(`CASE WHEN Email LIKE '%${inputs.Name}' 
      THEN 1 else 0 end` ), 'waaait']
    ],
     attributes: {exclude: ['Password', 'PasswordSalt']},
     where : {
       $or: [
         {GivenName:{$like: `%${inputs.Name}`}},
         {FamilyName:{$like: `%${inputs.Name}%`}},
         {Email: {$like: `%${inputs.Name}%`}}
       ]
     },
      order: [
     ['GivenName', (inputs.sort !== null) ? ((inputs.sort) === '-name' ? 'DESC' : 'ASC') : 'ASC']
   ]
   })).map(e => e.toJSON());

这不会产生与sql查询相同的结果。如何将一个案例评估返回的结果添加到下一个案例评估的结果中?

0 个答案:

没有答案