【问题标题】:Nestjs how to properly map 2 tables with a middle tableNestjs如何正确映射2个表和一个中间表
【发布时间】:2020-07-29 18:10:54
【问题描述】:

我使用Postgres 作为数据库有下一个表:

学生

id: Integer (PK)
name: Text

主题

id: Integer (PK)
name: Text

学生作业

student_id: Integer (PK)
subject_id: Integer (PK)

那些表没有Auto-generated PK。 所以,我的实体是:

Student.entity.ts

import { Entity, Column, PrimaryGeneratedColumn, OneToMany, PrimaryColumn } from 'typeorm';
import { student_assignation } from './student_assignation.entity';
import { Subject } from './subject.entity';

@Entity()
export class Student {
  @Column('number')
  @PrimaryColumn()
  id: number;

  @Column('text')
  name: string;

  @OneToMany(type => student_assignation, x => x.subject_id)
  //student_assignations: student_assignation[];
}

好吧,这是我的问题: 我正在尝试将所有主题分配给用户。 在SQL 术语中,我将其定义为:

SELECT 
    u.id, u.name, r.id, r.name
FROM  
    student u INNER JOIN student_assignation ra
        ON u.id = ra.student_id
    INNER JOIN subject r
        ON r.id = ra.subject_id
WHERE
    u.id = 1

但此刻在nestjs中转换和使用,我有这个关系:

@OneToMany(type => student_assignation, x => x.subject_id)

@ManyToOne(type => subject, x => x.id)

但是,没有检索任何信息。

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    您需要多对多关系。看看 TypeOrm 的实现here

    【讨论】:

      【解决方案2】:

      您必须在many-to-many 关系中实现您的实体:

      @Entity()
      export class Student {
          @Column('number')
          @PrimaryColumn()
          id: number;
      
          @Column('text')
          name: string;
      
          @ManyToMany(type => Subject)
          @JoinTable({ name: 'student_assignation' })
          subjects: Subject[];
      }
      
      
      @Entity()
      export class Subject {
          @PrimaryColumn()
          id: number;
      
          @Column()
          name: string;
      
          @ManyToMany(type => Student)
          students: Student[];
      }
      

      检索具有所有主题的用户:

      const user = await User.findOne(USER_ID, { relations: ['subjects'] })
      console.log(user.subjects);
      

      【讨论】:

        猜你喜欢
        • 2020-06-18
        • 1970-01-01
        • 2014-10-01
        • 2014-03-28
        • 2010-09-28
        • 1970-01-01
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        相关资源
        最近更新 更多