enco164
enco164

Reputation: 71

Include sub model in related model in loopback

I have Account model which hasMany Posts, and Post belongsTo Account

Account:

{
  "name": "Account",
  "base": "User",
  "relations": {
    "post": {
      "type": "hasMany",
      "model": "Post",
      "foreignKey": "accountId"
    },
...
  },
...
}

Post:

    {
      "name": "Post",
      "base": "PersistedModel",
      "relations": {
        "account": {
          "type": "belongsTo",
          "model": "Account",
          "foreignKey": ""
        }
      },
      ...
    }

Now, I have model Question which is sub model of Post model.

{
  "name": "Question",
  "base": "Post", ...
}

I want to query for specific Account all his fields and to include all his Questions with something like this

Account.findById({
        id: id,
        filter: {include: 'question'},
function(){...});

Is it possible?

Upvotes: 1

Views: 293

Answers (1)

conradj
conradj

Reputation: 2620

Account.findById(id, { include: { relation: 'questions' } }, function(){...});

You may need to create a questions relationship in the Account model, as I don't think it will inherit those from your Post model.

Note also that you should probably rename the post relationship to posts. So your relations section should look like:

Account:
{
  "name": "Account",
  "base": "User",
  "relations": {
    "posts": {
      "type": "hasMany",
      "model": "Post",
      "foreignKey": "accountId"
    },
    "questions": {
      "type": "hasMany",
      "model": "Question",
      "foreignKey": "accountId"
    }
...
  },
...
}

Upvotes: 1

Related Questions