3 路多对多类型Orm
3 way many-to-many typeOrm
有没有办法在 typeOrm 中实现 3 向多对多关系
3 向多对多关系的示例如下
3 way many-to-many relationship
我找到了解决方案;它实际上写在typorm的文档中
https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md#many-to-many-relations-with-custom-properties
与自定义属性的多对多关系
如果您需要为多对多关系添加额外的属性,您必须自己创建一个新实体。例如,如果您希望实体 Post 和 Category 与其他订单列具有多对多关系,则需要创建实体 PostToCategory,其中包含指向两个方向和自定义列的两个 ManyToOne 关系其中:
import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Post } from "./post";
import { Category } from "./category";
@Entity()
export class PostToCategory {
@PrimaryGeneratedColumn()
public postToCategoryId!: number;
@Column()
public postId!: number;
@Column()
public categoryId!: number;
@Column()
public order!: number;
@ManyToOne(type => Post, post => post.postToCategories)
public post!: Post;
@ManyToOne(type => Category, category => category.postToCategories)
public category!: Category;
}
此外,您还必须将如下关系添加到 Post 和类别:
// category.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.category)
public postToCategories!: PostToCategory[];
// post.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.post)
public postToCategories!: PostToCategory[];
有没有办法在 typeOrm 中实现 3 向多对多关系
3 向多对多关系的示例如下
3 way many-to-many relationship
我找到了解决方案;它实际上写在typorm的文档中 https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md#many-to-many-relations-with-custom-properties
与自定义属性的多对多关系 如果您需要为多对多关系添加额外的属性,您必须自己创建一个新实体。例如,如果您希望实体 Post 和 Category 与其他订单列具有多对多关系,则需要创建实体 PostToCategory,其中包含指向两个方向和自定义列的两个 ManyToOne 关系其中:
import { Entity, Column, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Post } from "./post";
import { Category } from "./category";
@Entity()
export class PostToCategory {
@PrimaryGeneratedColumn()
public postToCategoryId!: number;
@Column()
public postId!: number;
@Column()
public categoryId!: number;
@Column()
public order!: number;
@ManyToOne(type => Post, post => post.postToCategories)
public post!: Post;
@ManyToOne(type => Category, category => category.postToCategories)
public category!: Category;
}
此外,您还必须将如下关系添加到 Post 和类别:
// category.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.category)
public postToCategories!: PostToCategory[];
// post.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.post)
public postToCategories!: PostToCategory[];