使用内嵌对象分离关注点
对内嵌对象的支持是在 4.0 版本加入的
内嵌对象(embeddables)本身不是实体,但它们被内嵌到实体中并且可以被查询。你主要会用它们来减少重复或分离关注点。日期范围、地址这类值对象是该特性的主要使用场景。
内嵌对象需要像常规实体一样被发现,初始化 ORM 时别忘了把它们加入实体列表。
内嵌对象可以包含带基础 @Property() 映射的属性、嵌套的 @Embedded() 属性,或 @Embedded() 属性数组。从 5.0 版本起,你也可以使用 @ManyToOne() 属性。
在本教程中,我们假设你的应用中有一个 User 类,并且你想在 User 类中存储一个地址。Address 类会被建模为内嵌对象,而不是简单地把相应列直接加到 User 类上。
import { defineEntity, p } from '@mikro-orm/core';
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address),
},
});
const AddressSchema = defineEntity({
name: 'Address',
embeddable: true,
properties: {
street: p.string(),
postalCode: p.string(),
city: p.string(),
country: p.string(),
},
});
export class Address extends AddressSchema.class {}
AddressSchema.setClass(Address);
export class User extends UserSchema.class {}
UserSchema.setClass(User);import { type InferEntity, defineEntity, p } from '@mikro-orm/core';
export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address),
},
});
export type IUser = InferEntity<typeof User>;
export const Address = defineEntity({
name: 'Address',
embeddable: true,
properties: {
street: p.string(),
postalCode: p.string(),
city: p.string(),
country: p.string(),
},
});
export type IAddress = InferEntity<typeof Address>;import { Embeddable, Embedded, Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
@Embeddable()
export class Address {
@Property()
street!: string;
@Property()
postalCode!: string;
@Property()
city!: string;
@Property()
country!: string;
}
@Entity()
export class User {
@PrimaryKey()
id!: number;
@Embedded(() => Address)
address!: Address;
}import { Embeddable, Embedded, Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
@Embeddable()
export class Address {
@Property()
street!: string;
@Property()
postalCode!: string;
@Property()
city!: string;
@Property()
country!: string;
}
@Entity()
export class User {
@PrimaryKey()
id!: number;
@Embedded()
address!: Address;
}使用 ReflectMetadataProvider 时,你可能需要在装饰器选项中提供类:
@Embedded(() => Address)或@Embedded({ entity: () => Address })。
就数据库 schema 而言,MikroORM 会自动把 Address 类的所有列内联到 User 类的表中,就像你直接在那里声明它们一样。
初始化内嵌对象
如果内嵌对象中的所有字段都是可空的,你可能会想初始化该内嵌对象,以避免得到 null 值而不是内嵌对象本身。
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address)
.onCreate(() => new Address()),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address)
.onCreate(() => new Address()),
},
});@Embedded(() => Address)
address = new Address();@Embedded()
address = new Address();列前缀
默认情况下,MikroORM 会用值对象的名称作为前缀来命名你的列。
沿用上面的示例,你的列会被命名为 address_street、address_postal_code……
你可以通过修改 @Embedded() 记号中的 prefix 属性来改变这一行为以满足需求。
下面的示例展示了如何把前缀设为 myPrefix_:
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address).prefix('myPrefix_')
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address).prefix('myPrefix_')
},
});@Entity()
export class User {
@Embedded(() => Address, { prefix: 'myPrefix_' })
address!: Address;
}@Entity()
export class User {
@Embedded({ prefix: 'myPrefix_' })
address!: Address;
}你也可以用显式前缀更精确地决定列名如何生成。在下面的示例中:
relative模式(默认)会把前缀与其父级前缀(如果有)拼接起来,列名为contact_addr2_city、contact_addr2_street……absolute模式把前缀放在列的开头,列名为addr_city、addr_street……
const ContactSchema = defineEntity({
name: 'Contact',
embeddable: true,
properties: {
address: () => p.embedded(Address).prefix('addr_').prefixMode('absolute'),
address2: () => p.embedded(Address).prefix('addr2_').prefixMode('relative'),
},
});
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
contact: () => p.embedded(Contact),
},
});
export class Contact extends ContactSchema.class {}
ContactSchema.setClass(Contact);
export class User extends UserSchema.class {}
UserSchema.setClass(User);export const Contact = defineEntity({
name: 'Contact',
embeddable: true,
properties: {
address: () => p.embedded(Address).prefix('addr_').prefixMode('absolute'),
address2: () => p.embedded(Address).prefix('addr2_').prefixMode('relative'),
},
});
export type IContact = InferEntity<typeof Contact>;
export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
contact: () => p.embedded(Contact),
},
});
export type IUser = InferEntity<typeof User>;@Embeddable()
export class Contact {
@Embedded({ entity: () => Address, prefix: 'addr_', prefixMode: 'absolute' })
address!: Address;
@Embedded({ entity: () => Address, prefix: 'addr2_', prefixMode: 'relative' })
address2!: Address;
}
@Entity()
export class User {
@Embedded(() => Contact)
contact!: Contact;
}@Embeddable()
export class Contact {
@Embedded({ prefix: 'addr_', prefixMode: 'absolute' })
address!: Address;
@Embedded({ prefix: 'addr2_', prefixMode: 'relative' })
address2!: Address;
}
@Entity()
export class User {
@Embedded()
contact!: Contact;
}默认行为可以在 ORM 配置中覆盖:
MikroORM.init({
embeddables: {
prefixMode: 'absolute', // 默认为 `relative`
},
})要让 MikroORM 去掉前缀、直接使用值对象的属性名,请设置 prefix: false:
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address).prefix(false),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address).prefix(false),
},
});@Embedded({ entity: () => Address, prefix: false })
address!: Address;@Embedded({ prefix: false })
address!: Address;把内嵌对象存为对象
你也可以把内嵌对象存为一个对象,而不是把它的属性内联到拥有方实体中。
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address).object(),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
address: () => p.embedded(Address).object(),
},
});@Embedded({ entity: () => Address, object: true })
address!: Address;@Embedded({ object: true })
address!: Address;在 SQL 驱动中,这会使用一个 JSON 列来存储该值。
目前只有 MySQL 与 PostgreSQL 驱动支持按 JSON 属性搜索。
本部分文档深受 doctrine tutorial 启发,因为这里的行为与之几乎完全相同。
内嵌对象数组
内嵌数组始终以 JSON 形式存储。可以在嵌套的内嵌对象内部使用它们。
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
addresses: () => p.embedded(Address).array().onCreate(() => []),
},
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
addresses: () => p.embedded(Address).array().onCreate(() => []),
},
});@Embedded(() => Address, { array: true })
addresses: Address[] = [];@Embedded()
addresses: Address[] = [];查询内嵌数组
你可以直接查询内嵌数组元素的属性。MikroORM 会自动使用平台专属的 JSON 数组迭代生成相应的 SQL(例如 PostgreSQL 的 jsonb_array_elements、MySQL/MariaDB 的 json_table、SQLite 的 json_each)。
当指定多个属性条件时,它们必须全部匹配同一个数组元素(类似 MongoDB 的 $elemMatch):
// 查找有伦敦地址的用户
const users = await em.find(User, {
addresses: { city: 'London' },
});
// 查找有英国伦敦地址的用户(同一元素必须同时匹配两者)
const users = await em.find(User, {
addresses: { city: 'London', country: 'UK' },
});
// 运算符同样可用
const users = await em.find(User, {
addresses: { number: { $gt: 5 } },
});
// 数组元素作用域内的 $or/$and
const users = await em.find(User, {
addresses: { $or: [{ city: 'London' }, { city: 'Paris' }] },
});
// $not 查找没有任何元素匹配该条件的行(NOT EXISTS)
const users = await em.find(User, {
addresses: { $not: { city: 'London' } },
});
// 把 $not 与正向条件组合:
// 至少有一个元素在巴黎,且没有元素在伦敦
const users = await em.find(User, {
addresses: { $not: { city: 'London' }, city: 'Paris' },
});注意: 顶层
$not使用NOT EXISTS语义(没有任何数组元素匹配)。在$or/$and内部,$not则应用元素级取反(当前元素不匹配)。
$contains、$contained、$overlap 这类数组级运算符仍然照常工作,它们作用于整个数组列。
嵌套内嵌对象
你也可以嵌套内嵌对象,内联模式与对象模式都支持:
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
name: p.string(),
address: () => p.embedded(Address),
},
});
const ProfileSchema = defineEntity({
name: 'Profile',
embeddable: true,
properties: {
username: p.string(),
identity: () => p.embedded(Identity),
},
});
export class Profile extends ProfileSchema.class {}
ProfileSchema.setClass(Profile);
const IdentitySchema = defineEntity({
name: 'Identity',
embeddable: true,
properties: {
email: p.string(),
},
});
export class Identity extends IdentitySchema.class {}
IdentitySchema.setClass(Identity);
export class User extends UserSchema.class {}
UserSchema.setClass(User);export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
name: p.string(),
address: () => p.embedded(Address),
},
});
export type IUser = InferEntity<typeof User>;
export const Profile = defineEntity({
name: 'Profile',
embeddable: true,
properties: {
username: p.string(),
identity: () => p.embedded(Identity),
},
});
export type IProfile = InferEntity<typeof Profile>;
export const Identity = defineEntity({
name: 'Identity',
embeddable: true,
properties: {
email: p.string(),
},
});
export type IIdentity = InferEntity<typeof Identity>;import { Embeddable, Embedded, Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
@Entity()
export class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Embedded(() => Profile, { object: true, nullable: true })
profile?: Profile;
}
@Embeddable()
export class Profile {
@Property()
username: string;
@Embedded(() => Identity)
identity: Identity;
constructor(username: string, identity: Identity) {
this.username = username;
this.identity = identity;
}
}
@Embeddable()
export class Identity {
@Property()
email: string;
constructor(email: string) {
this.email = email;
}
}import { Embeddable, Embedded, Entity, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
@Entity()
export class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Embedded({ object: true })
profile?: Profile;
}
@Embeddable()
export class Profile {
@Property()
username: string;
@Embedded()
identity: Identity;
constructor(username: string, identity: Identity) {
this.username = username;
this.identity = identity;
}
}
@Embeddable()
export class Identity {
@Property()
email: string;
constructor(email: string) {
this.email = email;
}
}多态内嵌对象
同样可以使用多态内嵌对象。这意味着你可以为单个内嵌属性定义多个类,并根据判别列选用正确的那个,与单表继承的工作方式类似。
import { defineEntity, p } from '@mikro-orm/core';
export enum AnimalType {
CAT,
DOG,
}
const AnimalSchema = defineEntity({
name: 'Animal',
embeddable: true,
abstract: true,
discriminator: 'type',
properties: {
type: p.enum(() => AnimalType),
name: p.string(),
},
});
export class Animal extends AnimalSchema.class {}
AnimalSchema.setClass(Animal);
const CatSchema = defineEntity({
name: 'Cat',
embeddable: true,
extends: Animal,
discriminatorValue: AnimalType.CAT,
properties: {
canMeow: p.boolean().nullable(),
},
});
export class Cat extends CatSchema.class {}
CatSchema.setClass(Cat);
const DogSchema = defineEntity({
name: 'Dog',
embeddable: true,
extends: Animal,
discriminatorValue: AnimalType.DOG,
properties: {
canBark: p.boolean().nullable(),
},
});
export class Dog extends DogSchema.class {}
DogSchema.setClass(Dog);
const OwnerSchema = defineEntity({
name: 'Owner',
properties: {
id: p.integer().primary(),
name: p.string(),
pet: () => p.embedded([Cat, Dog]),
},
});
export class Owner extends OwnerSchema.class {}
OwnerSchema.setClass(Owner);import { defineEntity, p, type InferEntity } from '@mikro-orm/core';
export enum AnimalType {
CAT,
DOG,
}
export const Animal = defineEntity({
name: 'Animal',
embeddable: true,
abstract: true,
discriminator: 'type',
properties: {
type: p.enum(() => AnimalType),
name: p.string(),
},
});
export const Cat = defineEntity({
name: 'Cat',
embeddable: true,
extends: Animal,
discriminatorValue: AnimalType.CAT,
properties: {
canMeow: p.boolean().nullable(),
},
});
export const Dog = defineEntity({
name: 'Dog',
embeddable: true,
extends: Animal,
discriminatorValue: AnimalType.DOG,
properties: {
canBark: p.boolean().nullable(),
},
});
export const Owner = defineEntity({
name: 'Owner',
properties: {
id: p.integer().primary(),
name: p.string(),
pet: () => p.embedded([Cat, Dog]),
},
});
export type ICat = InferEntity<typeof Cat>;
export type IDog = InferEntity<typeof Dog>;
export type IOwner = InferEntity<typeof Owner>;import { Embeddable, Embedded, Entity, Enum, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
export enum AnimalType {
CAT,
DOG,
}
@Embeddable({ abstract: true, discriminator: 'type' })
export abstract class Animal {
@Enum(() => AnimalType)
type!: AnimalType;
@Property()
name!: string;
}
@Embeddable({ discriminatorValue: AnimalType.CAT })
export class Cat extends Animal {
@Property({ nullable: true })
canMeow?: boolean = true;
constructor(name: string) {
super();
this.type = AnimalType.CAT;
this.name = name;
}
}
@Embeddable({ discriminatorValue: AnimalType.DOG })
export class Dog extends Animal {
@Property({ nullable: true })
canBark?: boolean = true;
constructor(name: string) {
super();
this.type = AnimalType.DOG;
this.name = name;
}
}
@Entity()
export class Owner {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Embedded(() => [Cat, Dog])
pet!: Cat | Dog;
}import { Embeddable, Embedded, Entity, Enum, PrimaryKey, Property } from '@mikro-orm/decorators/legacy';
export enum AnimalType {
CAT,
DOG,
}
@Embeddable({ abstract: true, discriminator: 'type' })
export abstract class Animal {
@Enum()
type!: AnimalType;
@Property()
name!: string;
}
@Embeddable({ discriminatorValue: AnimalType.CAT })
export class Cat extends Animal {
@Property()
canMeow? = true;
constructor(name: string) {
super();
this.type = AnimalType.CAT;
this.name = name;
}
}
@Embeddable({ discriminatorValue: AnimalType.DOG })
export class Dog extends Animal {
@Property()
canBark? = true;
constructor(name: string) {
super();
this.type = AnimalType.DOG;
this.name = name;
}
}
@Entity()
export class Owner {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Embedded()
pet!: Cat | Dog;
}