【问题标题】:loopback relation to same model与同一模型的环回关系
【发布时间】:2016-04-21 17:35:49
【问题描述】:

我有一个如下的 FollowMap

{
      "name": "FollowMap",
      .
      .
      .
      "relations": {
        "follower_acc": {
          "type": "belongsTo",
          "model": "Account",
          "foreignKey": "follower_id"
        },
        "following_acc": {
          "type": "belongsTo",
          "model": "Account",
          "foreignKey": "following_id"
        }
      }
    }

我想与我的 Account 模型建立关系,这样我就可以获得一个用户关注者和关注列表,Account 模型如下;

{
  "name": "Account",
  .
  .
  .
    "followers": {
      "type": "hasMany",
      "model": "FollowMap",
      "foreignKey": "following_id"
    },
    "following": {
      "type": "hasMany",
      "model": "FollowMap",
      "foreignKey": "follower_id"
    }
  }
}

从关系中,我可以获取帐户的关注者和关注计数,但是,我无法从这些关系中获取关注者和关注的帐户列表。我希望它很清楚。

【问题讨论】:

    标签: node.js loopbackjs


    【解决方案1】:

    我知道这个问题可能已经过时了,但对于那些仍在寻找解决方案的人,我会给出我的。我想在我的数据库中实现配置文件实体之间的发布者/订阅者关系。

    最明显的方法是使用 hasAndBelongsToMany 关系,但奇怪的是你不能更改模型中使用的 foreignKey:这意味着你不能声明 "publishedId"“subscriberId” 用作引用 Profile 实体的外键。

    您必须手动声明用于引用这两个外键的第三个表。

    我的第三张表的工作示例:

    //common/models/subscribing.json
    {
      "name": "Subscribing",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {},
      "validations": [],
      "relations": {
        "subscriber": {
          "type": "belongsTo",
          "model": "Profil",
          "as": "subscriber"
        },
        "publisher": {
          "type": "belongsTo",
          "model": "Profil",
          "as": "publisher"
        }
      },
      "acls": [],
      "methods": {}
    }
    

    而我的 Profil 实体通过 Subscribings 表与自己相关:

    //common/models/profil.json
    {
      "name": "Profil",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
        "name": {
          "type": "string",
          "required": true
        }
      },
      "validations": [],
      "relations": {
        "followers": {
          "type": "hasMany",
          "model": "Profil",
          "foreignKey": "publisherId",
          "keyThrough": "subscriberId",
          "through": "Subscribing"
        },
        "subscribings": {
          "type": "hasMany",
          "model": "Profil",
          "foreignKey": "subscriberId",
          "keyThrough": "publisherId",
          "through": "Subscribing"
        }
      },
      "acls": [],
      "methods": {}
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      相关资源
      最近更新 更多