Sails.js 模型:创建 2 个与自身的关联失败
Sails.js Model: create 2 association to self failed
我对 Nodejs 和 sails 还很陌生。
我正在实现一个类似于 Twitter 的服务器。在用户模型中,应该有2个字段:follower和following,这2个字段是模型'user'本身的关联。
我的问题是当模型只有 1 个关联时,无论是关注者还是关注者,它都有效。
但是follower和following都包含的时候会报错
代码是这样的:
module.exports = {
attributes: {
alias: {
type:'string',
required: true,
primaryKey: true
},
pwd: {
type: 'string',
required: true
},
follower: {
collection: 'user',
via: 'alias'
},
following:{
collection: 'user',
via: 'alias'
}
}
代码会出现这样的错误:
usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115
throw new Error('Trying to associate a collection attribute to a model tha
^
Error: Trying to associate a collection attribute to a model that doesn't have a Foreign Key. user is trying to reference a foreign key in user
at References.findReference (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115:11)
at References.addKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:72:22)
对于这种用法,您的模型定义不正确,即 via
关键字。根据 waterline associations docs,via
关键字引用关联的另一端。因此,对于 follower
,另一侧是 following
,反之亦然。换句话说:
follower: {
collection: 'user',
via: 'following'
},
following:{
collection: 'user',
via: 'follower'
}
您可以在以下网址查看完整的工作示例:https://github.com/appscot/sails-orientdb/blob/master/test/integration-orientdb/tests/associations/manyToMany.selfReferencing.js
我对 Nodejs 和 sails 还很陌生。 我正在实现一个类似于 Twitter 的服务器。在用户模型中,应该有2个字段:follower和following,这2个字段是模型'user'本身的关联。
我的问题是当模型只有 1 个关联时,无论是关注者还是关注者,它都有效。 但是follower和following都包含的时候会报错
代码是这样的:
module.exports = {
attributes: {
alias: {
type:'string',
required: true,
primaryKey: true
},
pwd: {
type: 'string',
required: true
},
follower: {
collection: 'user',
via: 'alias'
},
following:{
collection: 'user',
via: 'alias'
}
}
代码会出现这样的错误:
usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115
throw new Error('Trying to associate a collection attribute to a model tha
^
Error: Trying to associate a collection attribute to a model that doesn't have a Foreign Key. user is trying to reference a foreign key in user
at References.findReference (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115:11)
at References.addKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:72:22)
对于这种用法,您的模型定义不正确,即 via
关键字。根据 waterline associations docs,via
关键字引用关联的另一端。因此,对于 follower
,另一侧是 following
,反之亦然。换句话说:
follower: {
collection: 'user',
via: 'following'
},
following:{
collection: 'user',
via: 'follower'
}
您可以在以下网址查看完整的工作示例:https://github.com/appscot/sails-orientdb/blob/master/test/integration-orientdb/tests/associations/manyToMany.selfReferencing.js