【发布时间】:2014-06-12 17:18:10
【问题描述】:
使用sails.js v0.10.0-rc7,我想保存一个用户和他的朋友。
我想我需要以某种方式创建从模型到自身的多对多关联?可能吗?
用户.js:
module.exports = {
attributes: {
name: {
type: 'string'
},
friends: {
collection: 'user',
via: ?
}
}
};
如果重要的话,我正在使用sails-mysql。 我发现了这个相关的问题,但没有解决我的问题:https://github.com/balderdashy/waterline/issues/410
谢谢!
更新: 到目前为止,我发现了两种方法,但都使用了冗余数据:
选项 1
按照hansmei的建议:
module.exports = {
attributes: {
id:{
type: 'integer',
autoIncrement: true,
primaryKey: true
},
name: {
type: 'string'
},
friends: {
collection: 'user',
via: 'id'
}
}
}
这需要我将每个友谊保存两次:
User.findOne(1).exec(function (err, user) {
user.friends.add(2);
...
User.findOne(2).exec(function (err, user) {
user.friends.add(1);
...
选项 2
attributes: {
name: {
type: 'string'
},
friends: {
collection: 'user',
via: 'friendOf',
dominant: true
},
friendOf:{
collection:'user',
via:'friends'
}
}
这也是多余的,因为友谊总是相互的。
(如果用户 A 是用户 B 的朋友,那么用户 B 必须是用户 A 的朋友)
有什么建议吗?
【问题讨论】: