Reputation: 33747
The problem I'm trying to solve is this. If I have product, I'd like to know what other products I can purchase as a combination that's on-sale. If this were MySQL, I'd set up my tables and queries like so:
t_product: product_id, product_name
t_combination: combination_id, on_sale
t_product_combination: combination_id, product_id
// what other products should I buy along with my product_id == 1 to get a good deal?
SELECT product_id
FROM t_product
WHERE product_id IN (
SELECT product_id
FROM t_combination_product
WHERE combination_id IN (
SELECT combination_id
FROM t_combination
WHERE on_sale = 'yes'
AND combination_id IN (SELECT combination_id FROM t_combination_product WHERE product_id = 1)
)
)
I tried to do this in realm react-native as shown below:
I have two collections: Product and a Combination, set up as follows
class Product {};
Product.schema = {
name: 'Product',
primaryKey:'productId',
properties: {
productId:'int',
product:'string'
}
};
class Combination {};
Combination.schema = {
name: 'Combination',
properties: {
onSale: {type: 'string'},
products: {type: 'list',objectType:'Product'},
}
};
What I want to do is given that I have Product.productId=1
, I want to find all other products that belong to Combinations that have Combination.onSale='yes'
and Product.productId IS IN (Combination.products )
.
This is the query I tried to do in realm with react-native:
let queryFilter = "ANY Combination.onSale = 'yes' AND Combination.products = 1";
let data = realm.objects('Product').objectsWhere(queryFilter);
But when I run this, I get the error
undefined is not a function (evaluating 'realm.objects('Product').objectsWhere(queryFilter)')
If I remove the objectsWhere(queryFilter)
, then it just returns me the list of all Products that hasn't been filtered.
So it seems I'm using objectsWhere incorrectly? How do I fix this to find a list of all products that are onsale if purchased with product 1?
Upvotes: 0
Views: 624
Reputation: 81588
If you had
class Product {};
Product.schema = {
name: 'Product',
primaryKey:'productId',
properties: {
productId:'int',
product:'string'
combinations: {type: 'linkingObjects', objectType: 'Combination', property: 'products'}
}
};
Backlink queries are not yet supported, so I think what you have to do is something like this:
let queryFilter = 'productId = 1';
let data = realm.objects('Product').filtered(queryFilter);
let combinations = data.combinations.filtered('onSale = true');
let linkedProducts = [];
for(let i = 0; i < combinations.length; i++) {
linkedProducts.push(combinations[i]);
}
// linked products should contain what you need
Upvotes: 1