A
A
alexeyinn2022-03-21 14:37:04
PostgreSQL
alexeyinn, 2022-03-21 14:37:04

Nest Postgresql Sequelize one-to-one ForeignKey error?

My table:

@Table({ tableName: "siCheckingInfo", createdAt: false, updatedAt: false })
export class SiChecking extends Model<SiChecking, CheckingAttrs> {
  @Column({
    type: DataType.INTEGER,
    unique: true,
    autoIncrement: true,
    primaryKey: true,
  })
  pageId: number;

  @Column({ type: DataType.STRING, allowNull: false })
  manufactureNum: string;

  *...some columns...*

  @Column({ type: DataType.STRING, allowNull: true })
  checkingType: string;

  @ForeignKey(() => CheckingDocs)
  @Column({ type: DataType.INTEGER })
  checkingDocsId: number;

  @BelongsTo(() => CheckingDocs)
  doc: CheckingDocs;

  @ForeignKey(() => SiType)
  @Column({ type: DataType.INTEGER })
  siTypeId: number;

  @BelongsTo(() => SiType)
  siType: SiType;

  **@ForeignKey(() => CheckingResults)
  @Column({ type: DataType.INTEGER })
  resultId: number;
  @HasOne(() => CheckingResults)
  results: CheckingResults;**
}


Linked to another table by a one-to-one relationship, to another table

@Table({ tableName: "checkingResults", createdAt: false, updatedAt: false })
export class CheckingResults extends Model<
  CheckingResults,
  CheckingResultsAttrs
> {
  @ForeignKey(() => SiChecking)
  @Column({
    type: DataType.INTEGER,
    unique: true,
    autoIncrement: true,
    primaryKey: true,
  })
  resultId: number;

  @Column({ type: DataType.BOOLEAN, unique: false, allowNull: false })
  isSuccessful: boolean;

*...some columns...*  

  @Column({ type: DataType.BOOLEAN, unique: false, allowNull: true })
  siIsSigned: boolean;

  @BelongsTo(() => SiChecking)
  SiChecking: SiChecking;
}


But when I try to add something to the second table, I get an error - Nest error insert or update in the table "checkingResults" violates the foreign key of the value "checkingResults_resultId_fkey"

I tried everything, but could not solve the problem.
And it seems to me that this error did not exist before. I did not touch these pieces of code, the error just appeared by itself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexeyinn, 2022-03-21
@alexeyinn

Issue resolved:
It was necessary to swap tables @HasOne and @BelongsTo
But there was a small other problem (or it should be):
If you build an ERD table schema in pgAdmin, then the image shows that the tables have a relationship - one-to-many but not one-to-one. Did he do something wrong in the models, or is this normal for the generated ERD circuit?62387f401fb70631121964.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question