我正在尝试创建过滤器
router.get('/resources', async (req, res) => {
const { myAttribute1, myAttribute2 } = req.query;
let query = {};
if (myAttribute1) {
query.myAttribute1 = { $like: myAttribute1 };
}
if (myAttribute2) {
query.myAttribute2 = { $like: myAttribute2 };
}
const resources = await findAll(query);
res.send(resources);
});
然后在模型中
export async function findAll(query) {
return await Resource.findAll({
where: {
...query
},
raw: true
}).then(result => {
return result;
}).catch(err => {
return err;
});
}
但是由于$like
被括在括号中而无法正常工作,有没有办法实现这一目标?
答案 0 :(得分:0)
我改变了
router.get('/resources', async (req, res) => {
const resources = await findAll(req.query);
res.send(resources);
});
然后在模型中
const Op = Sequelize.Op;
export async function findAll(query) {
const { myAttribute1, myAttribute2 } = req.query;
let params = {};
if (myAttribute1) {
query.myAttribute1 = { $like: myAttribute1 };
}
if (myAttribute2) {
query.myAttribute2 = { $like: myAttribute2 };
}
return await Resource.findAll({
where: {
...params
},
raw: true
}).then(result => {
return result;
}).catch(err => {
return err;
});
}