2017-03-09 19 views
0

我想基於標誌在Sequalize中添加「where」查詢。讓我知道如何得到這個。在基於標誌的Sequalize中添加「where」查詢

例如,如果標誌爲真,那麼我想添加這個「where」類,否則我不想添加「where」子句。

models.Users.findAll({ 
     where: { 
      email: req.query.email 
     } 
    }).then(function (list) { 
     res.send(list); 
    }).catch(function (error) { 
     res.status(500).json(error); 
    }); 



models.Users.findAll({ 
    }).then(function (list) { 
     res.send(list); 
    }).catch(function (error) { 
     res.status(500).json(error); 
    }); 
+0

什麼是國旗?一些外部布爾變量與模型沒有關聯? – piotrbienias

+0

是的..有些外部布爾值。對或錯 。 – JavaUser

回答

0

你可以用一個空的查詢對象開始,和where財產在適當的時候給它添加:

let query = {}; 

if (someCondition) { 
    query.where = { email: req.query.email }; 
} 
models.Users.findAll(query).then(...); 
+0

對不起。 – JavaUser

+1

@JavaUser你必須詳細說明「不工作」 – robertklep

0

您可以使用簡單的one-line if statementfindAll方法調用中。讓我們假設variable是你的布爾標誌

models.Users.findAll(variable ? { where: { email: req.query.email } } : {}).then(list => { 
    res.send(list); 
}).catch(error => { 
    res.status(500).json(error); 
}); 

或者你可以在options對象分配給一個變量,並使用相同if聲明,但findAll外呼

let options = variable ? { where: { email: req.query.email } } : {}; 

models.Users.findAll(options).then(list => { 
    // ... 
}); 
+0

對不起.... ts不工作。 – JavaUser

+1

你是什麼意思不工作?出現一些錯誤或發生了什麼? – piotrbienias

1

您可以創建JSON其中第一個你在where子句中提供,然後在where子句中傳遞它..類似於

var jsonObj = null ; 

if (req.query.email){ 
    jsonObj = {"email": req.query.email}; 
} else { 
    jsonObj = {"email": {$ne:null}}; //otherwise it will return all rows, if email is not null in your database 
} 

models.Users.findAll({ 
     where: jsonObj 
    }).then(function (list) { 
     res.send(list); 
    }).catch(function (error) { 
     res.status(500).json(error); 
    }); 

希望這會有幫助