1.0.2 • Published 4 years ago

loopback-filter-by-relations-mixin v1.0.2

Weekly downloads
8
License
MIT
Repository
github
Last release
4 years ago

loopback-filter-by-relations-mixin

NPM version NPM downloads Build Status Coverage Status

Features

  • filter items by properties in related models
  • supports 'hasMany', 'hasManyThrough', 'belongsTo' relations
  • works with nested relations
  • use as mixin

Installation

npm install loopback-filter-by-relations-mixin --save

How to use

Add the mixins property to your server/model-config.json like the following:

{
  "_meta": {
    "sources": [
      "loopback/common/models",
      "loopback/server/models",
      "../common/models",
      "./models"
    ],
    "mixins": [
      "loopback/common/mixins",
      "../common/mixins",
      "../node_modules/loopback-filter-by-relations-mixin"
    ]
  }
}

To use with your Models add the mixins attribute to the definition object of your model config.

{
  "name": "Customer",
  "mixins": {
    "FilterByRelations": true
  },
  "relations": {
    "orders": {
      "type": "hasMany",
      "model": "Order",
      "foreignKey": "customerId"
    }
  },
  "properties": {
    "id": "Number",
    "name": "String",
    "age": "Number"
  }
} 
{
  "name": "Order",
  "mixins": {
    "FilterByRelations": true
  },
  "relations": {
    "customer": {
      "type": "belongsTo",
      "model": "Customer",
      "foreignKey": "customerId"
    }
  },
  "properties": {
    "id": "Number",
    "name": "String",
    "price": "Number",
    "customerId": "Number"
  }
}

Then use in you queries like:

  {
    "where": {
      "<RelationName>": "<WhereCondition>"
    }
  }
Customer.find({
  where: {
    orders: {
      price: { gt: 1000 }
    }
  }
}
Order.find({
  where: {
    customer: {
      age: { gte: 18 }
    }
  }
});

License

MIT