1. 程式人生 > >react-native之Realm資料庫的使用(一)

react-native之Realm資料庫的使用(一)

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

未完待續..