I’m trying to create a query with typeorm and MySQL.
I keep getting the following error:
[Nest] 44806 – 12/09/2021, 2:37:03 PM ERROR [ExceptionsHandler]
ER_BAD_FIELD_ERROR: Unknown column ‘sort_order’ in ‘order clause’
QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column ‘sort_order’ in
‘order clause’
My query is:
const { limit, page: skip, userLat, userLng, searchQuery, weekday, startHour, endHour } = options;
let stores;
// get only stores that open in the start and end hours range
const openHoursQuery = `
'${startHour}' BETWEEN `from` AND `to` AND
'${endHour}' BETWEEN `from` AND `to`
AND weekday = ${weekday}
`;
// get the distance from user's location to each store
const getDistanceQuery = `
SQRT(
POW(69.1 * (lat - ${userLat}), 2) +
POW(69.1 * (${userLng} - `long`) * COS(lat / 57.3), 2)
) AS distance
`;
stores = this.storeRepository.createQueryBuilder('store')
.leftJoinAndSelect('store.hours', 'store_hours')
.addSelect(userLat && userLng ? getDistanceQuery : '')
.where(searchQuery ? `name LIKE '%${searchQuery}%'` : '')
.andWhere(weekday && startHour && endHour ? openHoursQuery : '')
.orderBy(userLat && userLng ? 'distance' : 'sort_order')//sort_order
.take(limit)
.skip(skip)
.getManyAndCount();
return stores;
The problem is caused by the “leftJoinAndSelect” method, when I comment the join the query executes without any problems.
My DB tables look like this:
TABLE: stores
COLUMNS: id, uuid, name, status, address, URL, email, lat, long, sort_order
Table: store_hours
COLUMNS: id, store_id, weekday, from, to, type