Realm-js: IN Operator for String values

Created on 6 May 2017  路  3Comments  路  Source: realm/realm-js

How to achieve the result in Realm, similar to the below SQL query
SELECT * FROM t1 WHERE string in ("test", "test1");

I tried below approach in Realm,
this.realm.objects('TestObject').filtered(['test', 'test1'].map((id) => 'string == ' + id).join(' OR '));
but ends up with the following error message.
'Error running tests:', { [Error: Predicate expressions must compare a keypath and another keypath or a constant value]
line: 76458,
column: 50,

It looks the approach only works for integer and not for string.
this.realm.objects('TestObject').filtered([1,2].map((id) => 'int == ' + id).join(' OR '));

The results can be achieved in following way, but do we have any other better approach?
this.realm.objects('TestObject').filtered('string = "test" or string = "test1"');

Most helpful comment

If you in fact have a property called string in your object, the former should work although you are probably missing the quotation marks. Try with

this.realm.objects('TestObject')
  .filtered(['test', 'test1'].map((id) => 'string = "' + id + '"').join(' OR '));

or perhaps better:

const values = ['test, 'test1'];
const result = this.realm.object('TestObject')
  .filtered(values.map(_id, index) => `string = $${index}`).join(' OR '), ...values);

All 3 comments

If you in fact have a property called string in your object, the former should work although you are probably missing the quotation marks. Try with

this.realm.objects('TestObject')
  .filtered(['test', 'test1'].map((id) => 'string = "' + id + '"').join(' OR '));

or perhaps better:

const values = ['test, 'test1'];
const result = this.realm.object('TestObject')
  .filtered(values.map(_id, index) => `string = $${index}`).join(' OR '), ...values);

Great. both the suggestion works fine.

@kristiandupont thanks but I think this should be a first class operator rather than having to write this code.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MihaelIsaev picture MihaelIsaev  路  3Comments

kevinnguy picture kevinnguy  路  3Comments

camslaz picture camslaz  路  4Comments

kontinuity picture kontinuity  路  3Comments

max-zu picture max-zu  路  3Comments