Search code examples
loopbackjsloopback

How can I filter a one-to-many model relationship so that only active records are returned?


In loopback 3, we have added a field called "active" to all our models using a mixin. When requesting a Model via the common query methods, we have added code to filter by the active flag and reject inactive records.

Now we wish to do the same thing for the relations. Whenever a relation is navigated, it should exclude all resources that are not active. How do you do that?


Solution

  • We added this to all our model json files:

      "scope": {
        "where": {
          "active": true
        }
      },
    

    The to delete, we had to add a mixin:

      module.exports = function(Model, options) {
        console.log(`Adding softDelete mixin to model ${Model.name}`);
        Model.once("attached", function() {
          Model.deleteById = function(id, auth, cb) {
            // If your tables follow the TableNameID pattern for Ids, then do this: 
            //   `UPDATE ${Model.name} SET active=0 WHERE ${Model.name}ID = ?`;
            var query = `UPDATE ${Model.name} SET active=0 WHERE ID = ?`;
    
            Model.dataSource.connector.query(query, [id], function(err, result) {
              if (err) {
                console.log(err);
              }
              cb(null, { Success: "Record Deleted" });
            });
          };
        });
      };