【问题标题】:Find object by realm.js通过 realm.js 查找对象
【发布时间】:2016-03-02 18:21:56
【问题描述】:

您好,我使用带有 react-native 的领域数据库。

我有 Item 架构并通过 id 找到一项。

var items = realm.objects('Item');
var item = items.filtered('id == $0', item_id);
console.log(item.name); // It should be printed name, but undefined

我找不到项目。所以使用 lodash。

var item = _.find(realm.objects('Item'), _.matchesProperty('id', item_id));
console.log(item.name); // print "ABCD"

如何通过 id 获取商品?

【问题讨论】:

    标签: react-native realm


    【解决方案1】:

    filtered 返回一个与 javascript Array 非常相似的 Results 对象。

    所以你的代码应该是:

    var items = realm.objects('Item').filtered('id == $0', item_id);
    var item = items[0];
    console.log(item.name); // should print the name
    

    【讨论】:

      【解决方案2】:

      realm.objectForPrimaryKey('Item', item_id)

      【讨论】:

      • 请考虑为您的答案添加一些解释。
      【解决方案3】:

      你可以使用objectForPrimaryKey函数,但必须设置primaryKey你的架构

      设置主键

      const BookSchema = {
        name: 'Book',
        primaryKey: 'id',
        properties: {
          id:    'int',    // primary key
          title: 'string',
          price: 'float'
        }
      };
      

      用法

      const findObject = realm.objectForPrimaryKey('Item', item_id);

      【讨论】:

        猜你喜欢
        • 2017-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 2022-11-10
        相关资源
        最近更新 更多