简体   繁体   中英

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

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:

在此处输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM