【问题标题】:Typeorm - insert object with foreign key using non-primary columnTypeorm - 使用非主列插入具有外键的对象
【发布时间】:2021-09-24 10:09:39
【问题描述】:

我想知道是否可以使用 typeorm 的外键以外的列将对象插入到表中,如下所示。

我有这些实体:

@Entity()
export class User {

 @PrimaryGeneratedColumn()
 id: number;
 
 @Index()
 @Column({ type: 'varchar', length: 30, unique: true })
  username: string;

 @OneToMany(type => Post, post => post.user)
 posts: Post[];
}

@Entity()
export class Post {

 @PrimaryGeneratedColumn()
 id: number;
 
 @Column({ type: 'varchar', length: 20})
  title: string;
  
  @Column({ type: 'varchar', length: 240})
  post: string;

 @ManyToOne(type => User, user => user.posts)
  @JoinColumn({name: 'user_id'})
  user: User;
}

我将帖子作为这样的对象:

{
    "title":"First post",
    "post":"Post content",
    "user": {
        "username":"myusername"
    }
}

是否可以在不先通过用户名查找用户的情况下插入这样的对象?

如果用户不存在,插入一个新用户也不会有问题。我的意思是在插入之前不需要找到它,因为用户名是唯一的。

【问题讨论】:

    标签: typescript postgresql nestjs typeorm


    【解决方案1】:

    是的,您可以在您的用户实体上使用“cascade: true”选项。添加将是:

     `@OneToMany(type => Post, post => post.user, { cascade: true }) posts: Post[];`
    

    现在保存共享的对象后,如果不存在用户将被创建

    请在此处阅读有关 typeorm 文档的更多信息:typeorm docs

    在级联部分下

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多