简体   繁体   中英

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.

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[];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM