与同一模型

时间:2016-04-21 17:35:50

标签: node.js loopbackjs

我有一个FollowMap如下

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

我想建立一个与我的帐户模型的关系,所以我可以得到一个用户关注者&以下列表中,帐户模型如下;

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

//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": {}
}