Typeorm关系一对多,多对一

时间:2019-03-25 06:11:00

标签: typeorm

我是Typeorm的新手,它是(角度和节点)和初学者。我想建立类型关系,即;一对多,一对多

这些是我的实体:

import{Entity, PrimaryGeneratedColumn,BaseEntity, Column,JoinColumn, ManyToOne,OneToMany} from "typeorm";
import { User } from "./user.entity";

@Entity()
export class Test extends BaseEntity  {

@PrimaryGeneratedColumn()
Testid: number;

@Column()
name: string;

@OneToMany(type => User, user => user.Test)
 user: User;
}

import { Entity, PrimaryGeneratedColumn, Column, BaseEntity, 
Check, OneToMany,OneToOne, JoinColumn, ManyToOne } from "typeorm";
import { Contains, IsInt,Length, IsEmail, IsFQDN,  Min, Max, IsPhoneNumber,ValidatorConstraint, IsDate } from "class-validator";
import { Test } from "./test.entity";

@Entity()
export class User extends BaseEntity {

@PrimaryGeneratedColumn()
UserId: number;

@Column({ unique: true })
@Length(8, 16)
Username: string;

@Column()
@Length(8, 16)
FirstName: string;

@Column()
@Length(8, 16)
LastName: string;


@Column()
@Length(10, 11)
Phone: string;

@Column()
@IsEmail()
@Length(8, 16)
Email: string;

@Column()
@Length(8, 16)
Password: string;


@Column()
@Length(8, 16)
Status: string;

@Column()
@IsDate()
DOB: Date;

@Column()
@Length(8,16)
Test:string;

@ManyToOne(type => Test, test => test.user)
tests: Test[];

}

建立连接我写了如下代码   DATABASE.SERVICE.TS:

createConnection() .then(async Connection =>{ const test1 = new Test() test1.name = "dsd"; await Connection.manager.save(test1);

   const test2 = new Test();
   test2.name = "dfg";
   await Connection.manager.save(test2);

   const user = new User();
   user.FirstName = "harshaaa";
   user.tests = [test1,test2]
   await Connection.manager.save(user.tests);

   const userRepository = Connection.getRepository(User);
   const users = await userRepository.find({ relations: ["tests"] });

   })

  

预期结果
  + ------------- + -------------- + -------------------- -------- + |用户|   + ------------- + -------------- + -------------------- -------- + | id | int(11)|主键AUTO_INCREMENT | |网址|   varchar(255)| | | userId | int(11)
  | |   + ------------- + -------------- + -------------------- -------- +

     

+ ----------------- + -------------- + ----------------- ----------- + |测试   + ------------- + -------------- + -------------------- -------- + | id | int(11)|主键AUTO_INCREMENT | |名称|   varchar(255)| |   + ------------- + -------------- + -------------------- -------- +

     

实际结果

我通过在用户详细信息中输入来获取用户详细信息。但同一个ID并未进入db中的测试实体

0 个答案:

没有答案