MikroORM7.2 中文文档
建模/JSON 属性
已译 96/96

JSON 属性

定义 JSON 属性

在 JSON 属性方面,各个数据库驱动的行为略有不同:有些会自动为你解析值,有些则会把它们作为 JSON 字符串返回。MikroORM 试图通过 JsonType 统一这一体验。如果你指定 type: 'json',同样会使用该类型。

@Entity()
export class Book {

  @Property({ type: 'json', nullable: true })
  meta?: { foo: string; bar: number };

}

按 JSON 对象属性查询

你可以按 JSON 对象属性查询。

你可以轻松地按 JSON 对象属性查询:

const b = await em.findOne(Book, {
  meta: {
    valid: true,
    nested: {
      foo: '123',
      bar: 321,
      deep: {
        baz: 59,
        qux: false,
      },
    },
  },
});

会生成如下查询(postgres 中):

select "e0".*
from "book" as "e0"
where ("meta"->>'valid')::bool = true
  and "meta"->'nested'->>'foo' = '123'
  and ("meta"->'nested'->>'bar')::float8 = 321
  and ("meta"->'nested'->'deep'->>'baz')::float8 = 59
  and ("meta"->'nested'->'deep'->>'qux')::bool = false
limit 1

目前所有驱动都受支持(包括 sqlite 与 mongo)。在 postgres 中,如果我们检测到右侧是数字或布尔值,还会尝试对该值做类型转换。

使用 $elemMatch 查询 JSON 数组元素

当某个 JSON 属性存储的是对象数组时,你可以使用 $elemMatch 运算符查询单个元素的属性。MikroORM 会生成一个 EXISTS 子查询,其中使用平台专属的 JSON 数组迭代(例如 PostgreSQL 的 jsonb_array_elements、MySQL/MariaDB 的 json_table、SQLite 的 json_each)。

类型会根据你的查询值自动推断 —— 无需任何 schema 提示:

@Entity()
export class Event {

  @Property({ type: 'json', nullable: true })
  tags?: { name: string; priority: number }[];

}

// 查找带有 "typescript" 标签的事件
const events = await em.find(Event, {
  tags: { $elemMatch: { name: 'typescript' } },
});

// 数值条件会被自动转换(例如 postgres 上的 ::float8)
const events = await em.find(Event, {
  tags: { $elemMatch: { priority: { $gt: 5 } } },
});

// 多个条件必须匹配同一个数组元素
const events = await em.find(Event, {
  tags: { $elemMatch: { name: 'typescript', priority: { $gte: 8 } } },
});

// $or/$and/$not 在 $elemMatch 内部同样可用
const events = await em.find(Event, {
  tags: { $elemMatch: { $or: [{ name: 'typescript' }, { name: 'rust' }] } },
});

$elemMatch 可以通过 $and 与数组级运算符组合使用:

const events = await em.find(Event, {
  $and: [
    { tags: { $elemMatch: { priority: { $gt: 5 } } } },
    { tags: { $contains: [{ name: 'typescript' }] } },
  ],
});

对于内嵌数组属性,元素级查询无需 $elemMatch 即可隐式生效,因为 ORM 从内嵌对象元数据中已知 schema。

JSON 属性上的索引

要在 JSON 属性上创建索引,请使用带点路径的实体级 @Index() 装饰器:

@Entity()
@Index({ properties: 'metaData.foo' })
@Index({ properties: ['metaData.foo', 'metaData.bar'] }) // 复合索引
export class Book {

  @Property({ type: 'json', nullable: true })
  metaData?: { foo: string; bar: number };

}

在 PostgreSQL 中,这会生成类似如下的查询:

create index "book_meta_data_foo_index" on "book" (("meta_data"->>'foo'));

要创建唯一索引,请使用 @Unique() 装饰器:

@Entity()
@Unique({ properties: 'metaData.foo' })
@Unique({ properties: ['metaData.foo', 'metaData.bar'] }) // 复合唯一索引
export class Book {

  @Property({ type: 'json', nullable: true })
  metaData?: { foo: string; bar: number };

}

在 MySQL 中,你也可以显式设置类型:

@Entity()
@Index({ properties: 'metaData.foo', options: { returning: 'char(200)' } })
export class Book {

  @Property({ type: 'json', nullable: true })
  metaData?: { foo: string; bar: number };

}

这会生成类似如下的查询:

alter table `book`
  add index `book_meta_data_foo_index`((json_value(`meta_data`, '$.foo' returning char(200))));

MariaDB 驱动不支持该特性。