react-native之Realm数据库的使用(一)

艾令秋
2023-12-01

realm数据库是一款小型数据库系统,可以支持多个平台,如android、ios、javascript等。当然了realm也是可以支持react-native的,官网有具体介绍,官网文档

安装realm

npm install --save realm

然后link

react-native link realm

或者

rnpm link realm

如果link不完全,可以手动检查添加

1.Add the following lines to android/settings.gradle:

include ':realm'
project(':realm').projectDir =new File(rootProject.projectDir,'../node_modules/realm/android')

2.Add the compile line to the dependencies in android/app/build.gradle:

dependencies {
    compile project(':realm')
}

3.Add the import and link the package in MainApplication.java:

import io.realm.react.RealmReactPackage; // add this import

public class MainApplication extends Application implements ReactApplication {
    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            new RealmReactPackage() // add this line
        );
    }
}

React-native中用到的realm是一款对象数据库,因此使用起来相关简单方便;
然后关于其操作:
1. 打开数据库的方式,按照其介绍有两种方式
其一、通过 open方法,eg:

// Define your models and their properties
const CarSchema = {
  name: 'Car',
  properties: {
    make:  'string',
    model: 'string',
    miles: {type: 'int', default: 0},
  }
};
const PersonSchema = {
  name: 'Person',
  properties: {
    name:     'string',
    birthday: 'date',
    cars:     'Car[]',
    picture:  'data?' // optional property
  }
};

Realm.open({schema: [CarSchema, PersonSchema]})
  .then(realm => {
    // Create Realm objects and write to local storage
    realm.write(() => {
      const myCar = realm.create('Car', {
        make: 'Honda',
        model: 'Civic',
        miles: 1000,
      });
      myCar.miles += 20; // Update a property value
    });

    // Query Realm for all cars with a high mileage
    const cars = realm.objects('Car').filtered('miles > 1000');

    // Will return a Results object with our 1 car
    cars.length // => 1

    // Add another car
    realm.write(() => {
      const myCar = realm.create('Car', {
        make: 'Ford',
        model: 'Focus',
        miles: 2000,
      });
    });

    // Query results are updated in realtime
    cars.length // => 2
  });

其二、通过new产生一个对象

const PersonSchema = {
  name: 'Person',
  properties: {
    name: 'string',
    testScores: 'double?[]'
  }
};

let realm = new Realm({schema: [PersonSchema, CarSchema]});

realm.write(() => {
  let charlie = realm.create('Person', {
    name: 'Charlie',
    testScores: [100.0]
  });

  // Charlie had an excused absense for the second test and was allowed to skip it
  charlie.testScores.push(null);

  // And then he didn't do so well on the third test
  charlie.testScores.push(70.0);
});
  1. 插入数据
let realm = new Realm({schema: [PersonSchema, CarSchema]});
realm.write(() => {
  let charlie = realm.create('Person', {
    name: 'Charlie',
    testScores: [100.0]
  });
});
  1. 查询数据

假设有表 Dog,下面获取Dog表所有数据。

let dogs = realm.objects('Dog'); // retrieves all Dogs from the Realm

有时候我们需要做数据筛选,可以这样写

query(name){
    let dogs = realm.objects('Dog');
    let tanDogs = dogs.filtered('color = "tan" AND name "'+name+'"');
}

具体的筛选条件可以用到下面这些

At the moment only a subset of the NSPredicate syntax is supported in the query language. Basic comparison operators ==, !=, >, >=, <, and <= are supported for numeric properties. ==, BEGINSWITH, ENDSWITH, and CONTAINS are supported for string properties. String comparisons can be made case insensitive by appending [c] to the operator: ==[c], BEGINSWITH[c] etc. Filtering by properties on linked or child objects can by done by specifying a keypath in the query eg car.color == 'blue'

有时候我们还需要排序

let hondas = realm.objects('Car').filtered('make = "Honda"');

// Sort Hondas by mileage
let sortedHondas = hondas.sorted('miles');

// Sort in descending order instead
sortedHondas = hondas.sorted('miles', true);

// Sort by price in descending order and then miles in ascending
sortedHondas = hondas.sorted(['price', true], ['miles']);

results也可以通过存储对象的链接对象进行排序,如:

let people = realm.objects('Person');

// Sort people by the milage of their cars
let sortedPeople = people.sorted('car.miles');

未完待续..

 类似资料: