Help needed to build predicates dynamically
EleniDnD opened this issue · 2 comments
Hello, I am having some trouble building a predicate dynamically.
What I mean is, I want to retrieve all items from a table that have a Status = 0 and Flag = 2.
If user has entered a search text, then i also want to filter with that text. (I want to dynamically do this for a bunch of other properties).
Lets say i keep a predicate on a variable and use it on my query like this:
db.select().from(myTable).where(pred).exec()
The default predicate will be this;
var pred = lf.op.and(myTable.Status.eq(0), myTable.Flag.eq(2))
When user has entered a SearchText, i want to be able to alter the predicate to this:
var pred = lf.op.and(myTable.Status.eq(0), myTable.Flag.eq(2), myTable.SearchableText.eq(userInput));
Since user can select many filters on my app, like text, dates, etc.. I want to be able to build the predicate based on user selections.
I tried building and passing an array like [myTable.Status.eq(0), myTable.Flag.eq(2)] to lf.op.and() but it doesnt work.
Any help would be appreciated
In case anybody runs into the same problem i managed to make it work using this:
https://github.com/google/lovefield/blob/master/demos/olympia_db/angular/demo.js#L342-L345
In my case i did this:
var predicates = [myTable.Status.eq(0), myTable.Flag.eq(2)];
if(userInput!=null && userInput.length>0)
predicates.push(myTable.SearchableText.eq(userInput));
var pred = lf.op.and.apply(null, predicates);
db.select().from(myTable).where(pred).exec();
You can also leverage the ES6 spread operator so that you don't need to call apply()
, as follows
const pred = lf.op.and(...predicates);