【问题标题】:Sails.js model - create associations to self?Sails.js 模型 - 创建与自我的关联?
【发布时间】: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 的朋友)

有什么建议吗?

【问题讨论】:

    标签: sails.js waterline


    【解决方案1】:

    我已经设法以这种方式与自我建立关联(至少对于本地磁盘存储而言)。它也应该适用于 MySQL。

    用户模型:

    module.exports = {
      attributes: {
        id:{
          type: 'integer',
          autoIncrement: true,
          primaryKey: true
        },
        name: {
          type: 'string'
        },
        friends: {
          collection: 'user',
          via: 'id'
        }
      }
    }
    

    我不确定这是否是有效的多对多关系,但我认为您可以对其进行调整以使其适合您:)

    【讨论】:

    • 谢谢,如果我这样做,我将不得不保存每个友谊两次,例如: User.findOne(1) user.friends.add(2); User.findOne(2) user.friends.add(1);
    • 我会进一步检查。给我几天时间:)
    • 很抱歉,我找不到更好的解决方案。这一切都归结为您如何最好地定义友谊:数据库方面。我相信将每个友谊存储两次是最好的方法。如果您想出更好的方法,请告诉我。
    【解决方案2】:

    这是我想在我的 Backbone.Sails 插件中解决的问题(直到 Waterline 解决它)。

    我已经完全重写了 Sails 蓝图,包括支持自引用多对多关联。在模型定义中,您只需采用所需的约定:

    /api/models/Person.coffee

    module.exports =
        attributes:
            friends:
                collection: "person"
                via: "_friends"
                dominant: true
            _friends:
                collection: "person"
                via: "friends"
    

    上面,friends 属性是要持久化的集合。当通过blueprints 持久化时,_friends 集合将镜像friends 集合,模仿任何添加或删除请求 - 这意味着friends 集合将是一个相互关系,不需要任何额外的代码客户端.

    您可以下载蓝图here。如果没有此插件的前端部分,它们将可以正常工作(尽管您需要编译它们或npm install coffee-script)。只需将它们包含在您的 /api/blueprints 文件夹中,sails (0.10) 就会提取它们。

    虽然我很欣赏这个解决方案远非理想,但它似乎是目前最好的解决方案(尤其是如果您使用蓝图来实现所有持久性)。更好的解决方法是生命周期回调 - 但它们不适用于 .add(id).remove(id) 函数。

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多