mikro-orm - ST_Distance_Sphere 使用 MySQL 驱动程序的 Mikro-orm 命令
问题描述
使用 MySQL,我正在尝试ST_Distance_Sphere
使用QueryBuilder
.
我有一个实体:
import { Entity, PrimaryKey, Property } from "mikro-orm";
@Entity({ tableName: "studio" })
export default class StudioEntity {
@PrimaryKey()
public id!: number;
@Property()
public name!: string;
@Property({ columnType: "point srid 4326" })
public geometry!: object;
}
我正在尝试:
export default class StudioStore {
private studioRepository: EntityRepository<StudioEntity>;
public constructor(ormClient: OrmClient) {
this.studioRepository = ormClient.em.getRepository(StudioEntity);
}
public async findPage(first: number): Promise<StudioEntity[]> {
const query = this.studioRepository.createQueryBuilder().select("*");
query.addSelect(
"ST_Distance_Sphere(`e0`.`geometry`, ST_GeomFromText('POINT(28.612849 77.229883)', 4326)) as distance",
);
query.orderBy({ distance: "ASC" });
return query.limit(first).getResult();
}
}
但我得到一个 ORM 错误:
尝试通过不存在的属性 StudioEntity.distance 进行查询
所以,我尝试向实体添加一个属性:
@Property({ persist: false })
public distance?: number;
但现在我得到一个 MySQL 错误:
“订单子句”中的未知列“e0.distance”
这是生成的 SQL 查询:
[query] select `e0`.*, ST_Distance_Sphere(`e0`.`geometry`, ST_GeomFromText('POINT(28.612849 77.229883)', 4326)) as distance from `studio` as `e0` order by `e0`.`distance` asc limit 5 [took 4 ms]
解决方案
您将需要回退到 knex,因为 QB 目前仅支持按顺序定义的属性字段。您还需要distance
像之前那样定义该虚拟属性,以便可以将值映射到实体。
https://mikro-orm.io/docs/query-builder/#using-knexjs
const query = this.studioRepository.createQueryBuilder().select("*");
query.addSelect("ST_Distance_Sphere(`e0`.`geometry`, ST_GeomFromText('POINT(28.612849 77.229883)', 4326)) as distance");
query.limit(first);
const knex = query.getKnexQuery();
knex.orderBy('distance', 'asc');
const res = await this.em.getConnection().execute(knex);
const entities = res.map(a => this.em.map(StudioEntity, a));
我必须说不是很好,完全忘记了可以按计算字段排序。将尝试在 v4 中解决这个问题。我认为它甚至可以作为您的第二种方法,因为 QB 可以简单地检查该属性是否为虚拟 (has persist: false
),然后它不会为其添加前缀。
编辑:从 3.6.6 开始,该方法persist: false
应该开箱即用
推荐阅读
- php - 为 Woocommerce 中的特定用户角色应用折扣
- node.js - 具有元素 ID 和嵌套元素的 Nodejs xpath 选择器不起作用
- continuous-integration - 如何设置 Appium 测试(WDIO-Mocha 测试)通过 BitRise 测试作业的 % 容差
- php - ORDER BY 中的 Doctrine DQL 注入
- c - 无法在 C 中返回正确的变量
- python - 放置我的 GUI 组件的最佳方式是什么
- php - 添加 site/index.php/city 作为 codeigniter url 路由不起作用
- docker - 将卷挂载到 Windows 容器
- reactjs - GraphQL 突变如何知道它正在修改哪个节点?数据库中的每个节点是否有唯一的全局节点 ID?
- mysql - 根据出现在不同表的列中的 id 选择一个表中的行,并且基于另一列有多个匹配项