如何在Sails js水线数据库关系中设置主键

问题描述 投票:0回答:1

我一直在研究官方文档中与Sails JS水线数据库的关系。但是我一直很难理解如何设置我的外键,就像在普通的mysql关系中一样。请注意,在问这个问题之前,我已经阅读了https://sailsjs.com/documentation/concepts/models-and-orm/associations的文档。

假设我有一个模型PersonalInfo.js

module.exports = {

  attributes: {

    fullName:{
      type: 'string',
      required: true
    },

    phone:{
     type: 'string',
     required: true
   },

   location:{
     type: 'string',
     required: true
   },

   age:{
     type: 'integer',
     required: true
   },

   email:{
     type: 'string',
     required: true
   },

   gender:{
    type: 'string',
    required: true
  },

  userId:{
    type: 'integer',
    required: true,
  }
  
  },

};

而且我还有另一个看起来像这样的模型Archived.js

module.exports = {

  attributes: {
    userId: {
      type: 'number',
      required: true,
      //unique: true,
    },
    comment:{
      type: 'string',
      required: true
    },
    createdBy:{
      type: 'number',
      required: true
    }
    
  },

};

已归档的项目具有个人信息。完全知道两个模型都包含userId属性,我想使用相关的personalInfo来获取已归档的项目,我该如何关联主键?

var archived = Archived.find().populate('personal');
node.js sails.js waterline
1个回答
0
投票

默认情况下,如果未指定帆,帆将生成主键id

如果要使用自定义数据作为主键,则可以覆盖模型中的id属性并提供columnName

id: {
  type: 'string',
  columnName: 'email_address',
  required: true
}

然后您可以使用以下方式找到记录:

await User.find({ id: req.param('emailAddress' });

Reference

在您的情况下,似乎每个archived都有一个personalInfo。因此,从one to one侧是archived,但从one to many侧是personalInfo。要对这些关系进行建模,您可以进行以下操作:

personalInfo.js

module.exports = {

  attributes: {

    fullName:{
      type: 'string',
      required: true
    },

    phone:{
     type: 'string',
     required: true
   },

   location:{
     type: 'string',
     required: true
   },

   age:{
     type: 'integer',
     required: true
   },

   email:{
     type: 'string',
     required: true
   },

   gender:{
    type: 'string',
    required: true
  },

  userId:{
    type: 'integer',
    required: true,
  },
  archives: {
    collection: 'archived',
    via: 'info'
  }

  },

};

archived.js

module.exports = {

  attributes: {
    userId: {
      type: 'number',
      required: true,
      //unique: true,
    },
    comment:{
      type: 'string',
      required: true
    },
    createdBy:{
      type: 'number',
      required: true
    },

    info: {
      model: 'personalinfo'  // sails works with small cases internally for models
    }

  },

};

一旦执行此操作,创建一个archive将是:

await Archive.create({
  ...

  // Set the User's Primary Key to associate the info with the archive.
  info: 123
});

现在,您终于可以在查询时填充info

var archived = Archived.find().populate('info');

© www.soinside.com 2019 - 2024. All rights reserved.