我有一个json数组,其中包含这样的条件
conditionArr = [{
"column": "customer_date",
"operator": "eq",
"type": "day",
"value": "-9"
"connect": "or"
},{
"column": "register_date",
"operator": "eq",
"type": "day",
"value": "-9",
"connect": "and"
},{
"column": "reading_date",
"operator": "eq",
"type": "day",
"value": "-9",
"connect": "or"
},{
"column": "submit_date",
"operator": "eq",
"type": "day",
"value": "-9",
}
];
我还没有看过任何有关如何在续集上创建动态op条件的文档。我想在这些条件下构建查询数组对象,并将其放在像这样的where子句中
var query = Helper.buildQuery(conditions,template.type_name);
UserData.findAll({
where: query,
raw: true
});
function buildQuery(conditions,templateType){ var query = Array(); var i = 0;
conditions.forEach(function () {
var column = conditions[i].column;
var value = conditions[i].value;
var type = conditions[i].type;
var operator = conditions[i].operator;
var connector = conditions[i].connect;
var queryObject = new Object();
if(column.startsWith('Data')){
var regex = RegExp('>(.*?)[-|\(]','gm');
var match;
var matches = [];
while ((match = regex.exec(column)) != null) {
matches.push(match[1]);
}
var temp_column = '';
var ii = 0;
matches.forEach( function() {
temp_column += matches[ii] + '.';
ii++;
});
temp_column = temp_column.substring(0, temp_column.length - 1);
column = temp_column;
}
if (value == 'null') {
queryObject = { [column]: null };
}
else if (type == 'day' || type == 'week' || type == 'month' || type == 'year') {
var target = moment(new Date()).add(value, type);
switch (type) {
case 'day':
target.hour(0).minute(0).second(0).millisecond(0);
break;
case 'week':
target.day(0).hour(0).minute(0).second(0).millisecond(0);
case 'month':
target.week(0).day(0).hour(0).minute(0).second(0).millisecond(0);
case 'year':
target.month(0).week(0).day(0).hour(0).minute(0).second(0).millisecond(0);
break;
default:
break;
}
var target_end = moment(target).add(1, type);
queryObject = { [column]: { [Op.gt]: target.toDate(), [Op.lt]:
target_end.toDate() } };
} else if (type == 'string' || conditions[i].type == 'integer' ||
conditions[i].type == 'date') {
if(type === 'string' && operator ==='eq'){
operator = 'like';
queryObject = { [column]: { [operator]: value } };
}
else if(type ==='integer' && operator ==='eq'){
queryObject = { [column]: value };
}
else{
queryObject = { [column]: { [operator]: value } };
}
}
query.push(queryObject);
i++;
return query;