WHERE
子句位于嵌套SELECT
内,即使它在Sequelize findAll()
的根对象中描述。
我的控制器:
const whereClause = req.query.search ? {
$or: [
'$Request.id$',
'$Request.action$', // TODO: change to action name
// '$Devices.id$',
// '$Devices.Article.manufacturer$',
// '$Devices.Article.model$',
'$OldHolder.displayname$',
'$NewHolder.displayname$',
].map(key => ({
[key]: {
$like: `%${req.query.search}%`,
}
}))
} : {
// default where
}
const items = await Request.findAll({
where: whereClause,
order: orderClause,
limit: req.query.rowsPerPage != -1 ? +req.query.rowsPerPage || total : total,
offset: req.query.page * req.query.rowsPerPage - req.query.rowsPerPage || 0,
attributes: [ 'id', 'created_at', 'action', 'old_holder', 'new_holder' ],
include: [
{
model: Device,
as: 'Devices',
attributes: ['id'],
through: {attributes: []},
include: [
{
model: Article,
attributes: ['manufacturer', 'model', 'image_thumb']
}
]
},
{
model: User,
as: 'OldHolder',
attributes: ['id', 'displayname']
},
{
model: User,
as: 'NewHolder',
attributes: ['id', 'displayname']
}
]
})
使用当前语法,我只能通过Request.id和Request.action进行搜索。
结果SQL:
SELECT `Request`.*, `Devices`.`id` AS `Devices.id`, `Devices->device_request`.`device_id` AS `Devices.device_request.device_id`, `Devices->device_request`.`request_id` AS `Devices.device_request.request_id`, `Devices->Article`.`id` AS `Devices.Article.id`, `Devices->Article`.`manufacturer` AS `Devices.Article.manufacturer`, `Devices->Article`.`model` AS `Devices.Article.model`, `Devices->Article`.`image_thumb` AS `Devices.Article.image_thumb`, `OldHolder`.`id` AS `OldHolder.id`, `OldHolder`.`displayname` AS `OldHolder.displayname`, `NewHolder`.`id` AS `NewHolder.id`, `NewHolder`.`displayname` AS `NewHolder.displayname`
FROM (
SELECT `Request`.`id`, `Request`.`created_at`, `Request`.`action`, `Request`.`old_holder`, `Request`.`new_holder`
FROM `request` AS `Request`
WHERE (`Request`.`id` LIKE '%stock%' OR `Request`.`action` LIKE '%stock%' OR `NewHolder`.`displayname` LIKE '%stock%')
ORDER BY `Request`.`created_at` DESC
LIMIT 0, 10) AS `Request`
LEFT OUTER
JOIN (`device_request` AS `Devices->device_request`
INNER JOIN `device` AS `Devices` ON `Devices`.`id` = `Devices->device_request`.`device_id`) ON `Request`.`id` = `Devices->device_request`.`request_id`
LEFT OUTER
JOIN `device_info` AS `Devices->Article` ON `Devices`.`device_info_id` = `Devices->Article`.`id`
LEFT OUTER
JOIN `user` AS `OldHolder` ON `Request`.`old_holder` = `OldHolder`.`id`
LEFT OUTER
JOIN `user` AS `NewHolder` ON `Request`.`new_holder` = `NewHolder`.`id`;
但我需要这个WHERE
例如在查询结束时,它可以正常工作。
是否可以将其移出嵌套的SELECT
子句?
请求与属于To Many的设备有关。