如何在领域反应原生中进行子查询或反向链接查询?

时间:2017-11-16 12:57:43

标签: react-native subquery realm

我试图解决的问题是这个。如果我有产品,我想知道我可以购买哪些其他产品作为销售的组合。如果这是MySQL,我会设置我的表和查询,如下所示:

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)
    )
)

我尝试在realm react-native中执行此操作,如下所示:

我有两个系列:产品和组合,设置如下

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'},
    }
};

我想要做的是Product.productId=1,我想查找属于具有Combination.onSale='yes'Product.productId IS IN (Combination.products )的组合的所有其他产品。

这是我试图用react-native做的查询:

let queryFilter = "ANY Combination.onSale = 'yes' AND Combination.products = 1";
let data = realm.objects('Product').objectsWhere(queryFilter);

但是当我运行它时,我收到了错误

  

undefined不是一个函数(评估   #&39; realm.objects('产品&#39)。objectsWhere(queryFilter)&#39)

如果我删除了objectsWhere(queryFilter),那么它只会返回尚未过滤的所有商品的列表。

所以看来我使用的对象不正确?如何解决此问题,以查找与产品1一起购买的所有产品清单?

1 个答案:

答案 0 :(得分:1)

如果你有

class Product {};
  Product.schema = {
    name: 'Product',
    primaryKey:'productId',
    properties: {
        productId:'int',
        product:'string'
        combinations: {type: 'linkingObjects', objectType: 'Combination', property: 'products'}
    }
};

尚不支持反向链接查询,所以我认为你必须做的是这样的事情:

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