Sails.js Model: create 2 association to self failed

≯℡__Kan透↙ 提交于 2019-11-30 05:01:38

问题


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.

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.

The code is something like this:

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)

回答1:


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

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



来源:https://stackoverflow.com/questions/29997942/sails-js-model-create-2-association-to-self-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!