Search code examples
javascriptloopbackjs

Loopback query with where inside include


I am trying to query my data the following way:

const filter = {where: {activity_id: activity_id, include: {relation: 'planGoal', scope: {where: {activity_goal_id: goal_id}}}}};

However this doesn't seem to work only the activity_id filter is applied and the wrong data is returned.

So my question is how do I query data within an include? and is it even possible?

For reference, here are the models in question:

    {
  "name": "plan_goal_has_action_option",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "type": "number"
    },
    "activity_id": {
      "type": "number"
    },
    "plan_has_goal_id": {
      "type": "number"
    },
    "action_option": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "planGoal": {
      "type": "belongsTo",
      "model": "plan_has_goal",
      "foreignKey": "plan_has_goal_id"
    }
  },
  "acls": [],
  "methods": {}
}


    {
  "name": "plan_has_goal",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "type": "number"
    },
    "activity_id": {
      "type": "number"
    },
    "activity_goal_id": {
      "type": "number"
    }
  },
  "validations": [],
  "relations": {
    "goal": {
      "type": "belongsTo",
      "model": "activity_goal",
      "foreignKey": "activity_goal_id"
    },
    "actions": {
      "type": "hasMany",
      "model": "plan_goal_has_action_option",
      "foreignKey": "plan_has_goal_id"
    }
  },
  "acls": [],
  "methods": {}
}

Solution

  • include and where are two different filters:

    {  
      where: {
        activity_id: activity_id
      },
      include: {  
        relation: 'planGoal',
        scope: {
          where: {
            activity_goal_id: goal_id
          }
        }
      }
    }