MikroORM7.2 中文文档
建模/复合主键与外键作主键
已译 96/96

复合主键与外键作主键

对复合主键的支持是在 3.5 版本加入的

MikroORM 原生支持复合主键。复合主键是非常强大的关系数据库概念,我们花了很大精力确保 MikroORM 支持尽可能多的复合主键使用场景。MikroORM 既支持原始数据类型的复合主键,也支持把外键作为主键。你还可以在关系中使用带复合主键的实体。

本节展示复合主键的语义如何运作,以及它们如何映射到数据库。

一般性考量

主键的值需要在调用 em.persist(entity) 之前设置好。

仅使用原始类型

假设你想建一个汽车数据库,并用车型名称与生产年份作为主键:

const CarSchema = defineEntity({
  name: 'Car',
  properties: {
    name: p.string(),
    year: p.integer(),
  },
  primaryKeys: ['name', 'year'],
});

export class Car extends CarSchema.class {}
CarSchema.setClass(Car);
export const Car = defineEntity({
  name: 'Car',
  properties: {
    name: p.string(),
    year: p.integer(),
  },
  primaryKeys: ['name', 'year'],
});
@Entity()
export class Car {

  @PrimaryKey()
  name: string;

  @PrimaryKey()
  year: number;

  // 这是 `FilterQuery` 中正确类型检查所必需的
  [PrimaryKeyProp]?: ['name', 'year'];

  constructor(name: string, year: number) {
    this.name = name;
    this.year = year;
  }

}
@Entity()
export class Car {

  @PrimaryKey()
  name: string;

  @PrimaryKey()
  year: number;

  // 这是 `FilterQuery` 中正确类型检查所必需的
  [PrimaryKeyProp]?: ['name', 'year'];

  constructor(name: string, year: number) {
    this.name = name;
    this.year = year;
  }

}

现在你可以使用这个实体了:

const car = new Car('Audi A8', 2010);
await em.persist(car).flush();

查询时你需要在条件中提供所有主键,或者按主键定义顺序提供主键数组:

const audi1 = await em.findOneOrFail(Car, { name: 'Audi A8', year: 2010 });
const audi2 = await em.findOneOrFail(Car, ['Audi A8', 2010]);

如果你想使用第二种主键元组的方式,需要像 Car 实体中那样通过 PrimaryKeyProp 符号指定实体主键的类型。

当你的实体只有一个标量主键,且属性名为以下之一时,不需要 PrimaryKeyProp:id: number | string | bigint、_id: any 或 uuid: string。

你也可以在关联中使用这个实体。此时 MikroORM 会为关联实体生成两个外键,一个指向 name,一个指向 year。

这个示例很好地解决了 em.persist() 之前必须有值的诉求:把它们作为构造函数的必填参数。

通过外联实体确定标识

有大量使用场景下,实体的标识应当由一个或多个父实体决定。

  • 实体的动态属性(例如 Article)。每篇文章有多个属性,主键为 article_id 与 attribute_name。
  • Person 的 Address 对象,地址的主键是 user_id。这不算复合主键,但标识是通过外联实体与外键推导出来的。
  • 带元数据的中间表可以建模为实体,例如两篇文章之间的关联,外加一段描述与一个评分。

通过外联实体映射标识的语义很简单:

  • 仅允许在 @ManyToOne 或 @OneToOne 关联上使用。
  • 在装饰器中使用 primary: true。

使用场景 1:动态属性

我们继续使用带任意属性的文章示例,映射如下:

const ArticleSchema = defineEntity({
  name: 'Article',
  properties: {
    id: p.integer().primary().autoincrement(),
    title: p.string(),
    attributes: () => p.oneToMany(ArticleAttribute).mappedBy('article').cascade(Cascade.ALL),
  },
});

export class Article extends ArticleSchema.class {}
ArticleSchema.setClass(Article);

const ArticleAttributeSchema = defineEntity({
  name: 'ArticleAttribute',
  properties: {
    article: () => p.manyToOne(Article).primary(),
    attribute: p.string().primary(),
    value: p.string(),
  },
  primaryKeys: ['article', 'attribute'],
});

export class ArticleAttribute extends ArticleAttributeSchema.class {}
ArticleAttributeSchema.setClass(ArticleAttribute);
export const Article = defineEntity({
  name: 'Article',
  properties: {
    id: p.integer().primary().autoincrement(),
    title: p.string(),
    attributes: () => p.oneToMany(ArticleAttribute).mappedBy('article').cascade(Cascade.ALL),
  },
});

export const ArticleAttribute = defineEntity({
  name: 'ArticleAttribute',
  properties: {
    article: () => p.manyToOne(Article).primary(),
    attribute: p.string().primary(),
    value: p.string(),
  },
  primaryKeys: ['article', 'attribute'],
});
@Entity()
export class Article {

  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;

  @OneToMany(() => ArticleAttribute, attr => attr.article, { cascade: Cascade.ALL })
  attributes = new Collection<ArticleAttribute>(this);

}

@Entity()
export class ArticleAttribute {

  @ManyToOne(() => Article, { primary: true })
  article: Article;

  @PrimaryKey()
  attribute: string;

  @Property()
  value!: string;

  [PrimaryKeyProp]?: ['article', 'attribute']; // 这是 `FilterQuery` 中正确类型检查所必需的

  constructor(name: string, value: string, article: Article) {
    this.attribute = name;
    this.value = value;
    this.article = article;
  }

}
@Entity()
export class Article {

  @PrimaryKey()
  id!: number;

  @Property()
  title!: string;

  @OneToMany(() => ArticleAttribute, attr => attr.article, { cascade: Cascade.ALL })
  attributes = new Collection<ArticleAttribute>(this);

}

@Entity()
export class ArticleAttribute {

  @ManyToOne({ primary: true })
  article: Article;

  @PrimaryKey()
  attribute: string;

  @Property()
  value!: string;

  [PrimaryKeyProp]?: ['article', 'attribute']; // 这是 `FilterQuery` 中正确类型检查所必需的

  constructor(name: string, value: string, article: Article) {
    this.attribute = name;
    this.value = value;
    this.article = article;
  }

}

使用场景 2:简单的派生标识

有时你会有这样的需求:两个对象通过 @OneToOne 关联关联起来,并且从属类应当复用它所依赖的那个类的主键。用户-地址关系就是一个很好的例子:

const UserSchema = defineEntity({
  name: 'User',
  properties: {
    id: p.integer().primary().autoincrement(),
    address: () => p.oneToOne(Address).inversedBy('user').cascade(Cascade.ALL),
  },
});

export class User extends UserSchema.class {}
UserSchema.setClass(User);

const AddressSchema = defineEntity({
  name: 'Address',
  properties: {
    user: () => p.oneToOne(User).primary(),
  },
  primaryKeys: ['user'],
});

export class Address extends AddressSchema.class {}
AddressSchema.setClass(Address);
export const User = defineEntity({
  name: 'User',
  properties: {
    id: p.integer().primary().autoincrement(),
    address: () => p.oneToOne(Address).inversedBy('user').cascade(Cascade.ALL),
  },
});

export const Address = defineEntity({
  name: 'Address',
  properties: {
    user: () => p.oneToOne(User).primary(),
  },
  primaryKeys: ['user'],
});
@Entity()
export class User {

  @PrimaryKey()
  id!: number;

  @OneToOne(() => Address, address => address.user, { cascade: [Cascade.ALL], nullable: true })
  address?: Address; // 虚拟属性(反向端),用于允许查询该关系

}

@Entity()
export class Address {

  @OneToOne(() => User, { primary: true })
  user!: User;

  [PrimaryKeyProp]?: 'user'; // 这是 `FilterQuery` 中正确类型检查所必需的

}
@Entity()
export class User {

  @PrimaryKey()
  id!: number;

  @OneToOne(() => Address, address => address.user, { cascade: [Cascade.ALL] })
  address?: Address; // 虚拟属性(反向端),用于允许查询该关系

}

@Entity()
export class Address {

  @OneToOne({ primary: true })
  user!: User;

  [PrimaryKeyProp]?: 'user'; // 这是 `FilterQuery` 中正确类型检查所必需的

}

使用场景 3:带元数据的连接表

在经典的订单-商品商店示例中,有订单项这一概念,它包含对订单与商品的引用,以及额外数据,比如购买商品的数量,甚至可能还有当前价格。

const OrderSchema = defineEntity({
  name: 'Order',
  properties: {
    id: p.integer().primary().autoincrement(),
    customer: () => p.manyToOne(Customer),
    items: () => p.oneToMany(OrderItem).mappedBy('order'),
    paid: p.boolean().default(false),
    shipped: p.boolean().default(false),
    created: p.datetime().onCreate(() => new Date()),
  },
});

export class Order extends OrderSchema.class {}
OrderSchema.setClass(Order);

const ProductSchema = defineEntity({
  name: 'Product',
  properties: {
    id: p.integer().primary().autoincrement(),
    name: p.string(),
    currentPrice: p.float(),
  },
});

export class Product extends ProductSchema.class {}
ProductSchema.setClass(Product);

const OrderItemSchema = defineEntity({
  name: 'OrderItem',
  properties: {
    order: () => p.manyToOne(Order).primary(),
    product: () => p.manyToOne(Product).primary(),
    amount: p.integer().default(1),
    offeredPrice: p.float(),
  },
  primaryKeys: ['order', 'product'],
});

export class OrderItem extends OrderItemSchema.class {}
OrderItemSchema.setClass(OrderItem);
export const Order = defineEntity({
  name: 'Order',
  properties: {
    id: p.integer().primary().autoincrement(),
    customer: () => p.manyToOne(Customer),
    items: () => p.oneToMany(OrderItem).mappedBy('order'),
    paid: p.boolean().default(false),
    shipped: p.boolean().default(false),
    created: p.datetime().onCreate(() => new Date()),
  },
});

export const Product = defineEntity({
  name: 'Product',
  properties: {
    id: p.integer().primary().autoincrement(),
    name: p.string(),
    currentPrice: p.float(),
  },
});

export const OrderItem = defineEntity({
  name: 'OrderItem',
  properties: {
    order: () => p.manyToOne(Order).primary(),
    product: () => p.manyToOne(Product).primary(),
    amount: p.integer().default(1),
    offeredPrice: p.float(),
  },
  primaryKeys: ['order', 'product'],
});
@Entity()
export class Order {

  @PrimaryKey()
  id!: number;

  @ManyToOne(() => Customer)
  customer: Customer;

  @OneToMany(() => OrderItem, item => item.order)
  items = new Collection<OrderItem>(this);

  @Property()
  paid = false;

  @Property()
  shipped = false;

  @Property()
  created = new Date();

  constructor(customer: Customer) {
    this.customer = customer;
  }

}

@Entity()
export class Product {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  @Property()
  currentPrice!: number;

}

@Entity()
export class OrderItem {

  @ManyToOne(() => Order, { primary: true })
  order: Order;

  @ManyToOne(() => Product, { primary: true })
  product: Product;

  @Property()
  amount = 1;

  @Property()
  offeredPrice: number;

  [PrimaryKeyProp]?: ['order', 'product']; // 这是 `FilterQuery` 中正确类型检查所必需的

  constructor(order: Order, product: Product, amount = 1) {
    this.order = order;
    this.product = product;
    this.offeredPrice = product.currentPrice;
  }

}
@Entity()
export class Order {

  @PrimaryKey()
  id!: number;

  @ManyToOne()
  customer: Customer;

  @OneToMany(() => OrderItem, item => item.order)
  items = new Collection<OrderItem>(this);

  @Property()
  paid = false;

  @Property()
  shipped = false;

  @Property()
  created = new Date();

  constructor(customer: Customer) {
    this.customer = customer;
  }

}

@Entity()
export class Product {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  @Property()
  currentPrice!: number;

}

@Entity()
export class OrderItem {

  @ManyToOne({ primary: true })
  order: Order;

  @ManyToOne({ primary: true })
  product: Product;

  @Property()
  amount = 1;

  @Property()
  offeredPrice: number;

  [PrimaryKeyProp]?: ['order', 'product']; // 这是 `FilterQuery` 中正确类型检查所必需的

  constructor(order: Order, product: Product, amount = 1) {
    this.order = order;
    this.product = product;
    this.offeredPrice = product.currentPrice;
  }

}
说明

默认情况下,底层会使用一个自动生成的中间表实体来表示中间表。你可以通过 pivotEntity 选项提供自己的实现。

该中间表实体必须恰好拥有两个 many-to-one 属性,其中第一个需要指向拥有方实体,第二个指向这个多对多关系的目标实体。

@Entity()
export class Order {

  @ManyToMany({ entity: () => Product, pivotEntity: () => OrderItem })
  products = new Collection<Product>(this);

}

对于双向 M:N 关系,只需在拥有方指定 pivotEntity 选项即可。你仍然需要通过 inversedBy 或 mappedBy 选项把两端关联起来。

@Entity()
export class Product {

  @ManyToMany({ entity: () => Order, mappedBy: o => o.products })
  orders = new Collection<Order>(this);

}

如果你想向这样的 M:N 集合添加新元素,那么所有非外键属性都必须定义数据库层面的默认值。

@Entity()
export class OrderItem {

  @ManyToOne({ primary: true })
  order: Order;

  @ManyToOne({ primary: true })
  product: Product;

  @Property({ default: 1 })
  amount!: number;

}

或者,你也可以直接操作中间表实体:

// 创建新条目
const item = em.create(OrderItem, {
  order: 123,
  product: 321,
  amount: 999,
});
await em.persist(item).flush();

// 或通过 delete 查询移除条目
const em.nativeDelete(OrderItem, { order: 123, product: 321 });

你也可以像上例那样定义指向中间表实体的 1:m 属性,并用它来修改集合,同时把 M:N 属性用于更便捷的读取与过滤。

在 QueryBuilder 中使用复合主键

在内部,复合主键被表示为元组,按主键定义的顺序包含所有值。

const qb1 = em.createQueryBuilder(CarOwner);
qb1.select('*').where({ car: { name: 'Audi A8', year: 2010 } });
console.log(qb1.getQuery());  // select `e0`.* from `car_owner` as `e0` where `e0`.`name` = ? and `e0`.`year` = ?

const qb2 = em.createQueryBuilder(CarOwner);
qb2.select('*').where({ car: ['Audi A8', 2010] });
console.log(qb2.getQuery());  // 'select `e0`.* from `car_owner` as `e0` where (`e0`.`car_name`, `e0`.`car_year`) = (?, ?)'

const qb3 = em.createQueryBuilder(CarOwner);
qb3.select('*').where({ car: [['Audi A8', 2010]] });
console.log(qb3.getQuery());  // 'select `e0`.* from `car_owner` as `e0` where (`e0`.`car_name`, `e0`.`car_year`) in ((?, ?))'

当你想获取带复合主键实体的引用时,同样适用:

const ref = em.getReference(Car, ['Audi A8', 2010]);
console.log(ref instanceof Car); // true

本部分文档深受 doctrine tutorial 启发,因为这里的行为与之几乎完全相同。