如何在 where 子句中使用动态查询字段

How to have a dynamic query field in where clause

本文关键字:动态 查询 字段 where 子句      更新时间:2023-09-26
   function check_model_owner(field, value, callback) { 
      Model.find({where: {field: value }}, function(err, models) {
            //code
         });
    }

此代码是从两个不同的地方调用的,接下来的内容对于两个调用都是相同的。

当然,现在这中断了,因为 where 子句中的field实际上在模型中不存在,应该用函数参数中的 field 变量代替。我能做到吗?

您可以创建查询对象:

function check_model_owner(field, value, callback) { 
  var query = {};
  query[field] = value;
  Model.find({where: query}, function(err, models) {
  });
}