本文介绍了Sails.js 模型:创建 2 个与自身的关联失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Nodejs 和风帆很陌生.我正在实现一个类似于 Twitter 的服务器.在用户模型中,应该有2个字段:follower和following,这2个字段是模型'user'本身的关联.

I'm pretty new on Nodejs and sails.I'm implementing a server which is similiar to Twitter. In user model, there should be 2 fields: follower and following, and the 2 fields are association of the model 'user' itself.

我的问题是当模型只有 1 个关联时,无论是关注者还是关注者,它都有效.但是,当follower和follower都包含时,就会报错.

My question is when the model have only 1 association, either follower or following, it works. However, when both follower and following included, there would be en error.

代码是这样的:

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

代码会导致这样的错误:

The code will cause such error:

    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> via 关键字引用关联的另一端.因此,对于 follower 来说,另一面是 following,反之亦然.换句话说:

For such usage your model definition is incorrect, namely the via keywords. As per the waterline associations docs the via keyword references the other side of the association. So, for a follower the other side is following and vice-versa. In other words:

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

You can check a full working example at: https://github.com/appscot/sails-orientdb/blob/master/test/integration-orientdb/tests/associations/manyToMany.selfReferencing.js

这篇关于Sails.js 模型:创建 2 个与自身的关联失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 10:42