创建表

一对多表

自己本表 对应 其他表多条数据

  1. import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm";
  2. import { Content } from "./typeorm.entity";
  3. @Entity('content_2')
  4. export class UserEntity {
  5. @PrimaryGeneratedColumn()
  6. id: number
  7. @Column()
  8. name: string
  9. // 本表一个 查询 content表多个
  10. @OneToMany(() => Content, content => content.user)
  11. content: Content[]// 一个查多个肯定是数组
  12. }

image.png

多对一表

  1. import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
  2. import { UserEntity } from "./user.entity";
  3. @Entity('content_1')
  4. export class Content {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string
  9. // 本表多个 查询 user表一个
  10. @ManyToOne(() => UserEntity, user => user.content)
  11. user: UserEntity
  12. }

自己表的多条数据可以对应其他表一条数据
image.png

查询数据

查询一对多

  1. return await getRepository(UserEntity)
  2. .createQueryBuilder('user')
  3. .leftJoinAndSelect('user.content','content') //1.要加载的关系 ,2.关系表别名
  4. .where('user.name = :name',{name:22})
  5. .getMany()
  6. // 查询到的数据
  7. {
  8. "code": 2000,
  9. "message": "请求成功!",
  10. "time": "2021-03-21T05:07:21.843Z",
  11. "data": [
  12. {
  13. "id": 2,
  14. "name": "22",
  15. "content": [ // 关联的content必定是数组,存放多条数据
  16. {
  17. "id": 1,
  18. "name": "111"
  19. },
  20. {
  21. "id": 2,
  22. "name": "222"
  23. }
  24. ]
  25. }
  26. ]
  27. }

查询多对一

本表多条数据对应其他表一条数据

  1. return await getRepository(Content)
  2. .createQueryBuilder('content')
  3. .leftJoinAndSelect('content.user','user')
  4. .where('content.name = :name',{name:111})
  5. .getMany()
  6. // 查询到的数据
  7. {
  8. "code": 2000,
  9. "message": "请求成功!",
  10. "time": "2021-03-21T05:09:18.509Z",
  11. "data": [
  12. {
  13. "id": 1,
  14. "name": "111",
  15. "user": { // 对应的一条数据
  16. "id": 2,
  17. "name": "22"
  18. }
  19. }
  20. ]
  21. }

疑惑

多对一表中的userid 是如何设置呢?动态填写参数?还是存储数据时候直接写死?如果小伙伴看到可以帮我解下疑惑,谢谢~~