SailsJs/Postgresql - How to create a one way association or one-to-many relation via an unique field

159 Views Asked by At

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.

1

There are 1 best solutions below

0
khushalbokadey On

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',
});