【问题标题】:Getting an error 'Unknown column' in 'order clause' using TypeORM使用 TypeORM 在“订单子句”中获取错误“未知列”
【发布时间】:2022-01-14 17:52:09
【问题描述】:

我正在尝试使用 TypeORM 和 MySQL 创建一个查询。 我不断收到以下错误:

[Nest] 44806 - 12/09/2021,下午 2:37:03 错误 [ExceptionsHandler] ER_BAD_FIELD_ERROR:“顺序子句”中的未知列“排序顺序” 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”方法引起的,当我评论连接时查询执行没有任何问题。

我的数据库表如下所示:

表格:商店

列:id、uuid、名称、状态、地址、URL、电子邮件、纬度、经度、排序顺序

表:store_hours

列:id、store_id、工作日、从、到、类型

编辑:

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

我现在有一个后续问题,当我使用“加入”方法时,按距离排序不起作用。

“距离”是我在选择中创建的附加字段,用于按与用户的距离对商店进行排序。

谢谢

【问题讨论】:

    标签: javascript mysql node.js database typeorm


    【解决方案1】:

    找到答案了。

    我应该使用 Alise 参数,而不是自己创建 alise。

    解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多