美文网首页
TypeOrm - 外键插入为Null

TypeOrm - 外键插入为Null

作者: 辻子路 | 来源:发表于2019-08-02 13:34 被阅读0次

    最近用nest尝试用typeorm写些数据库操作时,碰到子表保存数据时,外键一直为空。

    例如主表:

    
    import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, Generated, OneToMany } from 'typeorm';
    
    import { Post } from './post.entity';
    
    @Entity()
    
    export class User {
    
      @PrimaryGeneratedColumn()
    
      id: number;
    
      @Column()
    
      userName: string;
    
      @Column()
    
      password: string;
    
      @Column()
    
      haedImg: string;
    
      @Column({
    
        length: 11,
    
      })
    
      mobile: string;
    
      @CreateDateColumn({ type: 'timestamp' })
    
      createdAt: Date;
    
      @UpdateDateColumn({ type: 'timestamp' })
    
      updatedAt: Date;
    
      @OneToMany(type => Post, post => post.user)
    
      posts: Post[];
    
    }
    
    

    子表:

    
    import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, Generated, OneToMany, ManyToOne, JoinColumn } from 'typeorm';
    
    import { User } from './user.entity';
    
    @Entity()
    
    export class Post {
    
        @PrimaryGeneratedColumn()
    
        id: number;
    
        @Column()
    
        userId: number;  // 一定要定义一遍
    
        @ManyToOne(type => User, user => user.posts, { nullable: false })
    
        @JoinColumn({ name: 'userId' })
    
        user!: User;
    
        @Column('text')
    
        img: string;
    
        @Column('text')
    
        content: string;
    
        @Column({ default: 0 })
    
        shareCount: number;
    
        @Column({ default: 0 })
    
        commentCount: number;
    
        @Column({ default: 0 })
    
        likeCount: number;
    
        @Column({ default: 0 })
    
        collectCount: number;
    
        @CreateDateColumn({ type: 'timestamp' })
    
        createdAt: Date;
    
        @UpdateDateColumn({ type: 'timestamp' })
    
        updatedAt: Date;
    
    }
    
    

    原因是userId这个字段也还要再定义一遍,不然就会出现子表插入数据,userId为空的情况

    相关文章

      网友评论

          本文标题:TypeOrm - 外键插入为Null

          本文链接:https://www.haomeiwen.com/subject/kbkldctx.html