我有一个实体,其中包含一个名为“stats”的 json 对象。 Stats 有多个属性,我想通过这些属性来排序我的 findAll 方法。
我尝试了一切,但无法使用我的尝试让查询正常工作。
这就是我尝试查找按 stats.one_day_volume 属性排序的所有集合实体的方式
我使用下面显示的最后一种方法遇到的错误是 “表“stats”缺少 FROM 子句条目
const result = await getRepository(Collection)
.createQueryBuilder('collection')
.orderBy('collection.stats.one_day_volume', "DESC")
.take(take)
.skip(skip)
.getMany();
这是实体类
@Entity()
export class Collection {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({nullable:true})
external_link: string;
@Column({nullable:true})
description: string;
@Column()
slug: string;
@Column({nullable:true})
image_url: string;
@Column({nullable:true})
banner_image_url: string;
@Column()
dev_seller_fee_basis_points: string;
@Column()
safelist_request_status: string;
@Column({nullable:true})
payout_address: string;
@Column('jsonb')
primary_asset_contracts: AssetContract[];
@Column("simple-json")
traits: object;
@Column("jsonb", {array:true, nullable:true})
payment_tokens: PaymentToken[];
@Column("simple-array", {nullable:true})
editors: string[];
@Column("jsonb")
stats: CollectionStats;
@Column({ type: 'timestamptz' })
created_date: Date;
}
最佳答案
我还在寻找一种在 jsonb
列上 orderBy
的方法
但是当您尝试使用它getMany
时会出现问题。
所以我的解决方法是这样(使用 getRawMany 而不是 getMany):
const result = await getRepository(Collection)
.createQueryBuilder('collection')
.orderBy("collection.stats->>'one_day_volume'", "DESC")
.take(take)
.skip(skip)
.getRawMany();
很明显,使用 getRawMany
效果很好。
要将其作为实体,您可以尝试从存储库创建它,如下所示:
const repo = await getRepository(Collection);
const resultAsEntities = repo.create(result);
但看起来有时由于关系和其他对象的原因这不会按预期工作,因此您可以尝试通过这种方式实现它:
const resultIds = result.map(item => item.id);
const resultAsEntities = await getRepository(Collection).findByIds(resultIds);
关于postgresql - TypeORM 通过 json 属性查询具有 jsonb 列的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69864705/