Search code examples
javascriptbackbone.jsappcelerator-alloy

How to apply where condition to backbone query


I'm building an app with Appcelerator. I use Backbone to get data from database.

So I have build this code to get data from database:

var collection = Alloy.createCollection("SocialHistoryDAO");
collection.fetch();

Now I want to apply a where at this collection. So I use this code:

collection.where(id : 5);

Then this code works, but now I want to apply this filter:

"WHERE ID != 5";

It is possible to do this?

EDIT: this is my SocialHistoryDAO model:

exports.definition = {
    config: {
        columns: {
            "ID": "INTEGER PRIMARY KEY AUTOINCREMENT",
            "IdOmnia": "INTEGER",
            "DateStart": "text",
            "DateEnd": "text",
            "Quantity": "decimal",
            "Code": "text",
            "CodeSystem": "text",
            "DisplayName": "text",
            "DisplayNameTarget": "text",
            "UnityMeasure": "text",
            "StateID": "INTEGER"
        },
        adapter: {
            type: "sql",
            collection_name: "SocialHistoryDAO",
            idAttribute: "ID"
        }
    },
    extendModel: function(Model) {
        _.extend(Model.prototype, {
            // extended functions and properties go here
        });

        return Model;
    },
    extendCollection: function(Collection) {
        _.extend(Collection.prototype, {

            destroyAll : function(opt) {
              var db = Ti.Database.open(this.config.adapter.db_name);
              db.execute("DELETE FROM " + this.config.adapter.collection_name);
              db.close();
              this.models = [];
              if (!opt || !opt.silent) { this.trigger("reset"); }
              return this;
            }
        });

        return Collection;
    }
};

Solution

  • If you're using Backbone, then you're also using Underscore (or LoDash).

    This can be accomplished using either:

    var newArray = _.filter(collection.models, function(model) { return model.get('ID') != 5; });
    

    or

    var newArray = _.reject(collection.models, function(model) { return model.get('ID') == 5; });