简体   繁体   English

如何在 typeOrm 上建立关系

[英]how to make relationship on typeOrm

How do I define a relationship?如何定义关系?

@Entity('favoritesable')
export class FavoritesEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  favoritesableId: number; // foreing key ( ads id, blog id, user id )

  @Column()
  favoritesableType: string; // ads, blog, user

  @Column()
  userId: number;
}

ads entity:广告实体:

@Entity('ads')
export class AdsEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  // How do I define a relationship to FavoritesEntity ?

}

data example for favoritesable table:收藏表的数据示例:

{id: 1, favoritesableId: 1, favoritesableType: "ads", userId: 1},
{id: 2, favoritesableId: 4, favoritesableType: "ads", userId: 1},
{id: 3, favoritesableId: 1, favoritesableType: "ads", userId: 2},

how to make this relation on ads entity and favorites Entity?如何在广告实体和收藏实体上建立这种关系?

TypeORM's documentation pretty clearly shows ow to make a relationship between entities. TypeORM 的文档非常清楚地展示了如何在实体之间建立关系。

Example pulled from their docs:从他们的文档中提取的示例:

import {Entity, PrimaryGeneratedColumn, Column, ManyToMany} from "typeorm";
import {Question} from "./Question";

@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToMany(type => Question, question => question.categories)
    questions: Question[];

}
import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from "typeorm";
import {Category} from "./Category";

@Entity()
export class Question {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @Column()
    text: string;

    @ManyToMany(type => Category, category => category.questions)
    @JoinTable()
    categories: Category[];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该如何在nestjs typeorm中制作映射表关系逻辑? - How should i make mapping table relationship logic in the nestjs typeorm? 如何在两个表之间建立一对多关系,但将数据存储在第三个表中? 类型ORM - How to make One-to-Many relationship between two tables, but to store data in third table? TypeORM 如何创建如何在 typeorm 中创建多对多关系,[NestJS] - how to create how to create many to many relationship in typeorm, [NestJS] 如果没有这样的字段而是实体,如何在 TypeORM 中的 SELECT 中进行子查询? - How to make a subquery in SELECT in TypeORM if there is no such field but an entity? 如何使用 typeorm 在具有外键的两个实体之间创建关系 - how to create relationship between two entities with foreign key using typeorm 如何让 Inner Join 在 TypeORM 上工作? - How to make Inner Join to work on TypeORM? TypeORM:自定义多对多关系 - TypeORM: Custom Many To Many Relationship 如何使 Nestjs Typeorm 的枚举和 protobuf 的枚举兼容? - How to make Nestjs Typeorm's enum and protobuf's enum compatible? 如何在 typeorm、postgres 中组合 3 列唯一的? - How do I make combination of 3 columns in typeorm, postgres unique? 如何从 NestJS/TypeORM 中父的加入字段访问关系 ID - How to access relationship ID from Parent's joined field in NestJS/TypeORM
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM