3对多类型Orm [英] 3 way many-to-many typeOrm

查看:71
本文介绍了3对多类型Orm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在typeOrm中实现3对多关系

Is there a way to implement 3 way many-to-many relationship in typeOrm

一个三对多关系的例子就像

an example of a 3 way many-to-many relationship would be like

3种多对多关系

推荐答案

我找到了解决方案;它实际上是在typorm的文档中编写的

i found a solution for that; it is actually written in typorm's documentation https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md#many-to-many-relations-with-custom-properties

具有自定义属性的多对多关系如果您需要多对多关系的其他属性,则必须自己创建一个新实体.例如,如果您希望实体Post和Category与其他订单列具有多对多关系,则需要创建实体PostToCategory,其中具有两个同时指向两个方向的ManyToOne关系和其中的自定义列:

many-to-many relations with custom properties In case you need to have additional properties to your many-to-many relationship you have to create a new entity yourself. For example if you would like entities Post and Category to have a many-to-many relationship with additional order column, you need to create entity PostToCategory with two ManyToOne relations pointing in both directions and custom columns in it:

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;
}

此外,您还必须在帖子和类别"中添加如下所示的关系:

Additionally you will have to add a relationship like the following to Post and Category:

// category.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.category)
public postToCategories!: PostToCategory[];

// post.ts
...
@OneToMany(type => PostToCategory, postToCategory => postToCategory.post)
public postToCategories!: PostToCategory[];

这篇关于3对多类型Orm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆