使用 TypeORM 在'order clause'中获取错误'Unknown column'



我正在尝试用TypeORM和MySQL创建一个查询。我一直得到以下错误:

[Nest]44806-2021年9月12日下午2:37:03错误[ExceptionsHandler]ER_BAD_FIELD_ERROR:"order子句"中的未知列"sort_order"QueryFailedError:ER_BAD_FIELD_ERROR:中的未知列"sort_order"订单条款">

我的查询是:

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;

这个问题是由";leftJoinAndSelect;方法,当我对联接进行注释时,查询执行起来没有任何问题。

我的DB表如下所示:

表:存储

列:id,uuid,名称,状态,地址,URL,电子邮件,lat,long,sort_order

表:门店小时

COLUMNS:id,store_id,工作日,from,to,type

编辑:

我设法理解了这个问题,我不得不使用store.sortOrder,这是"商店"实体中的名称对应字段。

我现在有一个后续问题,当我使用"联接"方法时,按距离排序不起作用。

"distance"是我在select中创建的一个附加字段,用于根据与用户的距离对商店进行排序。

谢谢

找到了答案。

我应该使用Alise的论点,而不是自己创造Alise。

解决方案:

.addSelect(userLat && userLng ? getDistanceQuery : '', 'distance')
.orderBy(userLat && userLng ? 'distance' : 'store.sortOrder')

最新更新