TypeORM问题保存实体,级联为true

时间:2019-10-25 07:57:01

标签: nestjs typeorm

我将NestJS与TypeORM结合使用,并且试图保存与消息的用户对话。我将对话实体上的消息字段设置为 cascade:true 。但是当我尝试这段代码时:

const user3: User = { login: 'admin', createdBy: 'system', lastModifiedBy: 'system' };
const user4: User = { login: 'user', createdBy: 'system', lastModifiedBy: 'system' };
const message1: Message = { content: 'Hello How are you? ', createdBy: user3.login, lastModifiedBy: user3.login };
const conversation1: Conversation = { sender: user3, reciever: user4, messages: [message1] };
getConnection().getRepository(Conversation).save(conversation1);

它创建以下查询:

INSERT INTO "message"("id", "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate", "content", "conversationSenderId", "conversationRecieverId", "conversationDate") VALUES (?, ?, datetime('now'), ?, datetime('now'), ?, ?, ?, ?)
-- PARAMETERS: ["67348880-6897-47cb-92ef-5f66ffb2e88c","admin","admin","Hello How are you? ","b2420445-c8ee-4080-86b3-98ab12ef576b","09f3672d-9b2f-4f68-b47e-a7ca5d806ec6","2019-10-24 14:41:40.000"]

出现此错误:

{ [Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed] errno: 19, code: 'SQLITE_CONSTRAINT' }

我可以看到消息表的外键有问题,但是我不能解决它,因为它是处理创建的TypeORM库,而不是我。 我在互联网(文档,github,stackoverflow)上搜索未成功。 我认为这是TypeORM库中的错误,但我是其中的新手,所以我更愿意问我做错了什么

这是我的实体:

export abstract class BaseEntity {
  @ObjectIdColumn()
  @PrimaryGeneratedColumn('uuid')
  id?: string;

  @Column()
  createdBy?: string;

  @CreateDateColumn()
  createdDate?: Date;

  @Column()
  lastModifiedBy?: string;

  @UpdateDateColumn()
  lastModifiedDate?: Date;
}

@Entity('user')
export class User extends BaseEntity {
  @Column()
  login?: string;

  @OneToMany(type => Conversation, conversation => conversation.sender)
  sentConversations?: Conversation[];

  @OneToMany(type => Conversation, conversation => conversation.reciever)
  recievedConversations?: Conversation[];
}

@Entity()
export class Conversation {
  @PrimaryColumn()
  senderId?: string;

  @PrimaryColumn()
  recieverId?: string;

  @CreateDateColumn({ primary: true })
  date?: Date;

  @OneToMany(type => Message, message => message.conversation, { cascade: true })
  messages: Message[];

  @ManyToOne(type => User, user => user.sentConversations)
  @JoinColumn({ name: 'senderId' })
  sender?: User;

  @ManyToOne(type => User, user => user.recievedConversations)
  @JoinColumn({ name: 'recieverId' })
  reciever?: User;
}

@Entity('message')
export class Message extends BaseEntity {
  @Column({ length: 10000 })
  content: string;

  @ManyToOne(type => Conversation, conversation => conversation.messages)
  conversation?: Conversation;
}

在此存储库中,您将能够重现该错误: https://github.com/youtix/nest-typerorm-test

2 个答案:

答案 0 :(得分:0)

外键约束位于数据库表上。在RDBMS术语中,级联意味着它将通过每种关系传播。我相信您创建的adminID不是用户表中的用户。您需要先查询该用户,然后将其用于消息推送。这应该解决您的问题的人。

  1. 从用户中选择*,其中uname ='admin'
  2. 插入消息表,其中userId =(用户ID从1开始)

  3. 庆祝

答案 1 :(得分:0)

我检查了您的git项目,如果您在synchronize: false中更改了orm.config.js,则一切正常