ilker
ilker

Reputation: 67

loopback relation to same model

I have a FollowMap as follows

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

I want to build a relation to my Account model, so I can get one users follower & following list, the Account model is as follows;

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

From the relation, I can fetch a Account's follower and following count however, I can't fetch the follower and following Account list from these relations. I hope it's clear.

Upvotes: 0

Views: 842

Answers (1)

JeanSaigne
JeanSaigne

Reputation: 333

I know this issue is maybe outdated, but for those who are still looking for the solution, i'll give mine. I wanted to do implement the publisher/subscriber relation between the profils entities in my database.

The most obvious way to do it is with the hasAndBelongsToMany relation, but strangely you cannot change the foreignKey used in model: it means you cannot declare "publishedId" and "subscriberId" to be used as foreign keys referencing a Profil entity.

You have to declare manually the third table used to reference those 2 foreign keys.

My working example for this third table:

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

And my Profil entity related to itself through the Subscribings table:

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

Upvotes: 1

Related Questions