Tengo dos modelos: Categoría y Marcador. El marcador está asociado con la categoría a través de la columna categoryId.
La categoría también tiene columnas name , createdAt , orderId ;
Puedo obtener la categoría y todos sus marcadores con:
const category = await Category.findOne({ where: { id: req.params.id }, include: [ { model: Bookmark, as: 'bookmarks' }, ] }); Pero ahora quiero cambiar cómo se ordenan los marcadores. El tipo de pedido puede ser name , createdAt o orderId ;
const order = orderType == 'name' ? [[ { model: Bookmark, as: 'bookmarks' }, Sequelize.fn('lower', Sequelize.col('bookmarks.name')), 'ASC' ]] : [[{ model: Bookmark, as: 'bookmarks' }, orderType, 'ASC']] const category = await Category.findOne({ where: { id: req.params.id }, include: [ { model: Bookmark, as: 'bookmarks' }, ], order }); Funciona bien cuando orderType se createdAt o orderId pero falla cuando es el name
Recibo este error: SQLITE_ERROR: near \"(\": syntax error y la consulta SQL generada por Sequelize es:
SELECT `Category`.`id`, `Category`.`name`, `bookmarks`.`id` AS `bookmarks.id`, `bookmarks`.`name` AS `bookmarks.name`, `bookmarks`.`categoryId` AS `bookmarks.categoryId`, `bookmarks`.`orderId` AS `bookmarks.orderId`, `bookmarks`.`createdAt` AS `bookmarks.createdAt` FROM `categories` AS `Category` INNER JOIN `bookmarks` AS `bookmarks` ON `Category`.`id` = `bookmarks`.`categoryId` ORDER BY `bookmarks`.lower(`bookmarks`.`name`) ASC;Lo cambié a:
const order = orderType == 'name' ? [[Sequelize.fn('lower', Sequelize.col('bookmarks.name')), 'ASC']] : [[{ model: Bookmark, as: 'bookmarks' }, orderType, 'ASC']];y ahora está funcionando.