0

I have two models:

PdfAnnotation.js:

module.exports = {
  tableName: "pdf_annotations",
  primaryKey: "pk_id",

  attributes: {
    pk_id: {
      type: "number",
      autoIncrement: true
    },
    annotation_id: {
      type: "string",
      unique: true,
      required: true,
    },
    comments: {
      collection: "pdfcomments",
      via: "fk_annotation_id"
    }
  }
};

PdfComments.js:


module.exports = {
  tableName: "pdf_comments",
  primaryKey: "pk_id",

  attributes: {
    pk_id: {
      type: "number",
      autoIncrement: true,
    },
    fk_annotation_id: {
      model: "pdfannotations",
    },
    comment_content: {
      type: "string",
    },
  }
};

When I run these codes:

PdfAnnotations.create({
  annotation_id: "test3",
});
PdfComments.create({
  fk_annotation_id: 'test3',
  comment_content: 'test',
});

I got this error:

enter image description here

I have followed the documentation: https://sailsjs.com/documentation/concepts/models-and-orm/associations/one-to-many. The difference between my implementation and the docs is: the constraint I used for PdfComments to PdfAnnotations via an unique field annotation_id(string) not the primary key pk_id(number), so that I got the error.

For some reasons I don't want to use annotation_id as a primary key (such as its type is string)

I'm not familiar with Sails and its ORM, hope to see your help.

K. Tai
  • 136
  • 1
  • 8
  • `fk_annotation_id` expects the actual primary key id from PdfAnnotations model. So the row which got created during `PdfAnnotations.create`, the `id` of that should be passed for `fk_annotation_id`. – khushalbokadey May 30 '20 at 19:39
  • Hi @khushalbokadey, below the database I set the foreign key (fk_annotation_id) on pdf_comments table to reference pdf_annotation via annotation_id, so is there any way to set foreign key on ORM with specific field, currently seems like Sails ORM linking models/collections with primary key by default. Thanks – K. Tai May 31 '20 at 13:25

1 Answers1

0

Try something like this:

const pdfannotation = await PdfAnnotations.create({
  annotation_id: 'test3',
}).fetch();

const pdfcomment = await PdfComments.create({
  fk_annotation_id: pdfannotation.id,
  comment_content: 'test',
});
khushalbokadey
  • 1,132
  • 1
  • 11
  • 25