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



我一直在研究官方文档中与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
}

},
};

存档项目具有personalInfo。我非常清楚这两个模型都包含userId属性,我想获取具有相关personalInfo的存档项目,如下图所示,如何关联主键?

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

默认情况下,如果您没有指定主键id,则sails将生成主键。

如果您希望自定义数据作为主键,可以覆盖模型中的id属性,并给出columnName

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

然后,您可以使用查找记录

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

参考

在您的情况下,似乎每个archived都有一个personalInfo。这是来自archived侧的one to one,但是,来自personalInfo侧的one to many。为了建立这些关系的模型,在帆上你可以做一些类似的事情:

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

归档.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');

最新更新