我对Sails.js水线一对一的关联逻辑感到困惑

所以我之所以混淆,是因为我是一个PHP开发人员,很多时候使用Laravel和FuelPHP

我不明白的是它自己的联想。

我的意思是,我想创build一个基本的hasOne / BelongsTo逻辑,具体如下

用户有一个configuration文件

configuration文件属于一个用户

我习惯了以下build立(Laravel风格)

用户表

id | username | email | password --------------------------------------- 1 | My Username | My email | 1234568 

Users_profile表

 user_id | first_name | last_name ---------------------------------------- 1 | My First name | My Last name 

然后我只是这样定义模型

用户模型

 class Users extends Eloquent { public function profile() { return $this->hasOne('profile'); } } 

简介模型

 class Profile extends Eloquent { protected $tableName = 'users_profile'; protected $primaryKey = 'user_id'; public function user() { return $this->belongsTo('User'); } } 

它只是工作,因为return $this->hasOne('profile'); 会自动检查user_id

在Sails.js中尝试相同(以帆的方式)

用户模型

 module.exports = { attributes: { username: { type: 'string', unique: true, required: true }, email: { type: 'string', unique: true, email: true, required: true }, password: { type: 'string', required: true }, profile: { model: "profile", } }, }; 

简介模型

 module.exports = { tableName: 'user_profile', autoPK: false, autoCreatedAt: false, autoUpdateddAt: false, attributes: { user_id: { type: 'integer', primaryKey: true }, first_name: { type: 'string', }, last_name: { type: 'string', }, user: { model: "user" } } }; 

现在从文档中读取我必须以这种方式更新我的表格

 id | username | email | password | profile ------------------------------------------------- 1 | My Username | My email | 1234568 | 1 user_id | first_name | last_name | user | ----------------------------------------------- 1 | My First name | My Last name | 1 

所以我需要再次存储2个ID,我真的不明白为什么。

比我读进一步尝试使用via没有工作(注意,是为collections)

那么,有没有人能给我一个Laravelis风格的逻辑例子?

关于这个在文档(更简单的方法)什么也没有,因为在我看来,如果用户将有更多的关系,这将导致和身份证(只是我的aopinion)

Sails没有完全支持一对一的联系是一个已知的问题 ; 您必须将外键设置为您希望从哪个方面填充。 也就是说,如果你想让User #1链接到Profile #1并能够执行User.find(1).populate('profile') ,你可以设置User #1的profile属性,自动表示做Profile.find(1).populate('user')将工作。 这与Sails中的多对多关系相反,在其中添加链接就足够了。 这是因为多对多关系使用连接表,而一对一关系则不使用连接表。

这在Sails中并不是一个优先事项,因为一对一的关系通常不是很有用。 除非你有一个非常有说服力的理由 ,否则你最好把两个模型合并成一个模型。

在任何情况下,如果确实需要,可以使用.afterCreate生命周期callback来确保双向链接,例如在User.js

 module.exports = { attributes: {...}, afterCreate: function(values, cb) { // If a profile ID was specified, or a profile was created // along with the user... if (values.profile) { // Update the profile in question with the user's ID return Profile.update({id: values.profile}, {user: values.id}).exec(cb); } // Otherwise just return return cb(); } }; 

您可以添加类似的.afterCreate()Profile.js来处理在创buildconfiguration文件时更新受影响的用户。