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不是函数(正在求值'realm.objects('Product').objectsWhere(queryFilter)')

如果我删除objectsWhere(queryFilter),它只会返回所有未筛选的产品的列表。

看来我用的对象哪里不对?如果与产品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

相关内容

  • 没有找到相关文章

最新更新