멋진 커뮤니티 모듈

fibjs에 대한 객체 관계형 매핑

빌드 상태

설치하다

1
npm install fib-orm

시험

1
npm run ci

DBMS 지원

  • MySQL 및 마리아DB
  • SQLite

특징

fib-orm은 node-orm 객체에 동기 버전 메서드 세트를 추가합니다.

소개

이것은 fibjs 객체 관계형 매핑 모듈입니다.

예:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
var orm = require("fib-orm"); var db = orm.connectSync("mysql://username:password@host/database"); var Person = db.define("person", { name : String, surname : String, age : Number, // FLOAT male : Boolean, continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type photo : Buffer, // BLOB/BINARY data : Object // JSON encoded }, { methods: { fullName: function () { return this.name + ' ' + this.surname; } }, validations: { age: orm.enforce.ranges.number(18, undefined, "under-age") } }); // add the table to the database db.syncSync(); // add a row to the person table Person.createSync({ id: 1, name: "John", surname: "Doe", age: 27 }); // query the person table by surname var people = Person.findSync({ surname: "Doe" }); // SQL: "SELECT * FROM person WHERE surname = 'Doe'" console.log("People found: %d", people.length); console.log("First person: %s, age %d", people[0].fullName(), people[0].age); people[0].age = 16; people[0].saveSync();

node.js 버전은 다음과 같습니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
var orm = require("orm"); orm.connect("mysql://username:password@host/database", function (err, db) { if (err) throw err; var Person = db.define("person", { name : String, surname : String, age : Number, // FLOAT male : Boolean, continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type photo : Buffer, // BLOB/BINARY data : Object // JSON encoded }, { methods: { fullName: function () { return this.name + ' ' + this.surname; } }, validations: { age: orm.enforce.ranges.number(18, undefined, "under-age") } }); // add the table to the database db.sync(function(err) { if (err) throw err; // add a row to the person table Person.create({ id: 1, name: "John", surname: "Doe", age: 27 }, function(err) { if (err) throw err; // query the person table by surname Person.find({ surname: "Doe" }, function (err, people) { // SQL: "SELECT * FROM person WHERE surname = 'Doe'" if (err) throw err; console.log("People found: %d", people.length); console.log("First person: %s, age %d", people[0].fullName(), people[0].age); people[0].age = 16; people[0].save(function (err) { // err.msg = "under-age"; }); }); }); }); });

선적 서류 비치

Fibjs는 새로운 기능을 추가하지 않았으며 문서 개발은 node-orm을 참조할 수 있으며 비동기 호출을 동기 버전으로 변경하기만 하면 됩니다. wiki .

설정

Wiki 의 정보를 참조하세요 .

연결 중

Wiki 의 정보를 참조하세요 .

모델

모델은 하나 이상의 데이터베이스 테이블에 대한 추상화입니다. 모델은 연관을 지원합니다(자세한 내용은 아래 참조). 모델 이름은 테이블 이름과 일치하는 것으로 간주됩니다.

모델은 테이블 데이터에 액세스하고 조작하기 위한 동작을 지원합니다.

모델 정의

Wiki 의 정보를 참조하세요 .

Properties

Wiki 의 정보를 참조하세요 .

Instance Methods

모델 정의 중에 전달됩니다.

1 2 3 4 5 6 7 8 9 10 11 12 13
var Person = db.define('person', { name : String, surname : String }, { methods: { fullName: function () { return this.name + ' ' + this.surname; } } }); var person = Person.getSync(4); console.log( person.fullName() );

Model Methods

모델에서 직접 정의됩니다.

1 2 3 4 5 6 7 8 9
var Person = db.define('person', { name : String, height : { type: 'integer' } }); Person.tallerThan = function(height) { return this.findSync({ height: orm.gt(height) }); }; var tallPeople = Person.tallerThan( 192);

모델 로드 [지원되지 않음]

모델은 별도의 모듈에 있을 수 있습니다. 모델을 보유하는 모듈이 module.exports를 사용하여 데이터베이스 연결을 허용하는 함수를 게시하고 원하는 대로 모델을 로드하는지 확인하기만 하면 됩니다.

참고 - 이 기술을 사용하면 계단식 부하가 발생할 수 있습니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// your main file (after connecting) db.loadSync("./models"); // loaded! var Person = db.models.person; var Pet = db.models.pet; // models.js module.exports = function (db) { db.loadSync("./models-extra"); db.define('person', { name : String }); }; // models-extra.js module.exports = function (db) { db.define('pet', { name : String }); };

모델 동기화

Wiki 의 정보를 참조하세요 .

모델 삭제

Wiki 의 정보를 참조하세요 .

고급 옵션

defineORM2를 사용하면 모델 정의에 대한 몇 가지 고급 조정이 가능합니다. 설정을 통해 또는 모델을 설정할 때 호출을 통해 이를 구성할 수 있습니다 .

예를 들어 각 모델 인스턴스에는 데이터베이스에 고유 ID가 있습니다. 이 테이블 열은 자동으로 추가되며 기본적으로 "id"라고 합니다.
자체 key: true열을 정의하면 "id"가 추가되지 않습니다.

1 2 3 4 5 6 7 8 9 10 11 12
var Person = db.define("person", { personId : { type: 'serial', key: true }, name : String }); // You can also change the default "id" property name globally: db.settings.set("properties.primary_key", "UID"); // ..and then define your Models var Pet = db.define("pet", { name : String });

애완동물UID 모델에는 과 의 2개 열이 있습니다 name.

복합 키를 갖는 것도 가능합니다:

1 2 3 4
var Person = db.define("person", { firstname : { type: 'text', key: true }, lastname : { type: 'text', key: true } });

다른 옵션:

  • identityCache : (기본값: false) trueID 캐시( Singletons )를 활성화하거나 시간 초과 값(초)을 설정하도록 설정합니다.
  • autoSave : (기본값: ) 속성을 변경한 후 바로 인스턴스를 저장하도록 false설정합니다 .true
  • autoFetch : (기본값: ) 데이터베이스에서 인스턴스를 가져올 때 연관을 가져오도록 false설정합니다 .true
  • autoFetchLimit: (기본값: 1) autoFetch활성화된 경우 자동으로 가져올 후프(연관 연관) 수를 정의합니다.

후크

Wiki 의 정보를 참조하세요 .

아이템 찾기

Model.getSync(id, [ options ])

데이터베이스에서 특정 요소를 얻으려면 Model.get.

1 2
var person = Person.getSync(123); // finds person with id = 123

Model.findSync([ conditions ] [, options ] [, limit ] [, order ])

하나 이상의 요소를 찾는 데는 더 많은 옵션이 있으며 각 요소는 특정 매개변수 순서 없이 제공될 수 있습니다. options뒤에만 있어야 합니다 conditions(빈 개체인 경우에도).

1 2
var people = Person.findSync({ name: "John", surname: "Doe" }, 3); // finds people with name='John' AND surname='Doe' and returns the first 3

결과를 제한하거나 정렬하기를 원하기 때문에 결과를 정렬해야 하는 경우 다음을 수행하십시오.

1 2 3 4 5 6
var people = Person.findSync({ surname: "Doe" }, "name"); // finds people with surname='Doe' and returns sorted by name ascending people = Person.findSync({ surname: "Doe" }, [ "name", "Z" ]); // finds people with surname='Doe' and returns sorted by name descending // ('Z' means DESC; 'A' means ASC - default)

무언가를 찾기 위해 전달할 수 있는 더 많은 옵션이 있습니다. 이러한 옵션은 두 번째 개체에 전달됩니다.

1 2
var people = Person.findSync({ surname: "Doe" }, { offset: 2 }); // finds people with surname='Doe', skips the first 2 and returns the others

검색할 때 원시 SQL을 사용할 수도 있습니다. 이는 아래 연결 섹션에 설명되어 있습니다.

Model.countSync([ conditions])

조건과 일치하는 항목 수만 계산하려는 경우 항목을 모두 찾아 계산하는 대신 사용할 수 있습니다 .count(). 이는 실제로 데이터베이스 서버에 계산을 수행하도록 지시합니다(노드 프로세스 자체에서는 수행되지 않음). ).

1 2
var count = Person.countSync({ surname: "Doe" }); console.log("We have %d Does in our db", count);

Model.existsSync([ conditions])

와 마찬가지로 .count()이 메서드는 개수가 0보다 큰지 여부만 확인합니다.

1 2
var exists = Person.existsSync({ surname: "Doe" }); console.log("We %s Does in our db", exists ? "have" : "don't have");

Aggregating Functions

Array몇몇 속성만 선택하기 위해 of 속성을 전달할 수 있으며, 조건 Object을 정의하는 데에도 An을 사용할 수 있습니다.

다음은 사용 방법을 설명하는 예입니다 .groupBy().

1 2 3
//The same as "select avg(weight), age from person where country='someCountry' group by age;" var stats = Person.aggregate(["age"], { country: "someCountry" }).avg("weight").groupBy("age").getSync(); // stats is an Array, each item should have 'age' and 'avg_weight'

기본 .aggregate()방법

  • .limit(): 숫자를 제한으로 전달하거나 각각 오프셋과 제한으로 두 개의 숫자를 전달할 수 있습니다.
  • .order(): 같은Model.find().order()

추가 .aggregate()방법

  • min
  • max
  • avg
  • sum
  • count(바로가기가 있습니다 - Model.count)

드라이버에 따라 더 많은 집계 함수가 있습니다(예: 수학 함수).

Chaining

덜 복잡한 구문을 선호한다면 .find()콜백 매개변수를 제공하지 않고 연결할 수 있습니다.

1 2 3
var people = Person.find({ surname: "Doe" }).limit(3).offset(2).only("name", "surname").runSync(); // finds people with surname='Doe', skips first 2 and limits to 3 elements, // returning only 'name' and 'surname' properties

하나 또는 두 개의 속성만 건너뛰려면 .omit()대신 호출하면 됩니다 .only.

연결을 사용하면 더 복잡한 쿼리가 가능합니다. 예를 들어 사용자 정의 SQL을 지정하여 검색할 수 있습니다.

1
Person.find({ age: 18 }).where("LOWER(surname) LIKE ?", ['dea%']).allSync( ... );

오류가 발생하기 쉽고 애플리케이션이 SQL 삽입에 노출되므로 SQL 매개변수를 수동으로 이스케이프하는 것은 좋지 않습니다. 구문은 쿼리의 물음표를 제공된 매개변수로 안전하게 대체하여 이스케이프를 처리합니다. 다음과 같이 여러 절을 ?연결할 수도 있습니다. where필요합니다.

.find, .where& .all동일한 작업을 수행합니다. 모두 상호 교환 가능하고 연결 가능합니다.

order또는 다음을 수행할 수도 있습니다 orderRaw.

1 2 3
Person.find({ age: 18 }).order('-name').allSync( ... ); // see the 'Raw queries' section below for more details Person.find({ age: 18 }).orderRaw("?? DESC", ['age']).allSync( ... );

체인을 연결하여 마지막에 카운트만 얻을 수도 있습니다. 이 경우 오프셋, 제한 및 순서는 무시됩니다.

1 2
var people = Person.find({ surname: "Doe" }).countSync(); // people = number of people with surname="Doe"

선택한 항목을 제거하는 옵션도 사용할 수 있습니다. 체인 제거는 후크를 실행하지 않습니다.

1 2
Person.find({ surname: "Doe" }).removeSync(); // Does gone..

일반적인 배열 순회 방법을 사용하여 인스턴스를 수정하고 결국 모든 것을 저장할 수도 있습니다. [지원되지 않음]

1 2 3 4 5 6 7 8 9 10 11 12 13
Person.find({ surname: "Doe" }).each(function (person) { person.surname = "Dean"; }).save(function (err) { // done! }); Person.find({ surname: "Doe" }).each().filter(function (person) { return person.age >= 18; }).sort(function (person1, person2) { return person1.age < person2.age; }).get(function (people) { // get all people with at least 18 years, sorted by age });

물론 이 작업을 에서 직접 수행할 수도 .find()있지만 좀 더 복잡한 작업의 경우 이는 매우 유용할 수 있습니다.

Model.find()배열을 반환하지 않으므로 직접 연결할 수 없습니다. 연결을 시작하려면 호출해야 합니다 .each()(목록을 순회하려는 경우 선택적 콜백 사용). 그런 다음 공통 함수를 두 번 이상 사용할 .filter().sort()있습니다 .forEach().

마지막에(또는 프로세스 중에..) 다음을 호출할 수 있습니다.

  • .countSync()얼마나 많은 항목이 있는지 알고 싶다면;
  • .getSync()목록을 검색하려면;
  • .saveSync()모든 항목 변경 사항을 저장합니다.

정황

조건은 모든 키가 속성(테이블 열)인 객체로 정의됩니다. 모든 키는 논리 에 의해 연결되어야 합니다 AND. 를 전달하지 않는 한 값은 정확히 일치하는 것으로 간주됩니다 Array. 이 경우에는 부동산을 비교할 목록입니다.

1 2
{ col1: 123, col2: "foo" } // `col1` = 123 AND `col2` = 'foo' { col1: [ 1, 3, 5 ] } // `col1` IN (1, 3, 5)

다른 비교가 필요한 경우 일부 도우미 함수에 의해 생성된 특수 개체를 사용해야 합니다. 이를 설명하는 몇 가지 예는 다음과 같습니다.

1 2 3 4 5 6 7 8 9 10 11
{ col1: orm.eq(123) } // `col1` = 123 (default) { col1: orm.ne(123) } // `col1` <> 123 { col1: orm.gt(123) } // `col1` > 123 { col1: orm.gte(123) } // `col1` >= 123 { col1: orm.lt(123) } // `col1` < 123 { col1: orm.lte(123) } // `col1` <= 123 { col1: orm.between(123, 456) } // `col1` BETWEEN 123 AND 456 { col1: orm.not_between(123, 456) } // `col1` NOT BETWEEN 123 AND 456 { col1: orm.like(12 + "%") } // `col1` LIKE '12%' { col1: orm.not_like(12 + "%") } // `col1` NOT LIKE '12%' { col1: orm.not_in([1, 4, 8]) } // `col1` NOT IN (1, 4, 8)

원시 쿼리

1 2 3 4 5 6 7 8 9 10 11 12 13
var data = db.driver.execQuerySync("SELECT id, email FROM user") // You can escape identifiers and values. // For identifier substitution use: ?? // For value substitution use: ? var data = db.driver.execQuerySync( "SELECT user.??, user.?? FROM user WHERE user.?? LIKE ? AND user.?? > ?", ['id', 'name', 'name', 'john', 'id', 55]) // Identifiers don't need to be scaped most of the time var data = db.driver.execQuerySync( "SELECT user.id, user.name FROM user WHERE user.name LIKE ? AND user.id > ?", ['john', 55])

Identity pattern

ID 패턴을 사용할 수 있습니다(기본적으로 꺼져 있음). 활성화된 경우 여러 개의 서로 다른 쿼리가 동일한 결과를 가져오므로 동일한 객체를 얻게 됩니다. 데이터베이스를 변경할 수 있는 다른 시스템이 있거나 일부 매뉴얼을 호출해야 하는 경우 SQL 쿼리에서는 이 기능을 사용하면 안 됩니다. 또한 복잡한 자동 가져오기 관계에서 몇 가지 문제를 일으키는 것으로 알려져 있습니다. 사용에 따른 책임은 사용자에게 있습니다.

모델별로 활성화/비활성화할 수 있습니다.

1 2 3 4 5
var Person = db.define('person', { name : String }, { identityCache : true });

또한 전 세계적으로:

1 2
var db = orm.connectSync('...'); db.settings.set('instance.identityCache', true);

부울 대신 숫자를 전달하여 일정 시간 후에 만료되도록 ID 캐시를 구성할 수 있습니다. 이 숫자는 초 단위의 캐시 시간 초과로 간주됩니다(부동 소수점 사용 가능).

참고 : 캐싱에 대한 한 가지 예외는 인스턴스가 저장되지 않으면 사용되지 않는다는 것입니다. 예를 들어 Person을 가져온 다음 변경하면 저장되지 않는 동안 캐시에서 전달되지 않습니다.

아이템 생성

Model.createSync(items)

데이터베이스에 새 요소를 삽입하려면 Model.create.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var items = Person.createSync([ { name: "John", surname: "Doe", age: 25, male: true }, { name: "Liza", surname: "Kollan", age: 19, male: false } ]); // items - array of inserted items

항목 업데이트 중

반환된 모든 항목에는 모델에 정의된 속성과 각 항목을 변경하는 데 사용할 수 있는 몇 가지 메서드가 있습니다.

1 2 3 4 5
var John = Person.getSync(1); John.name = "Joe"; John.surname = "Doe"; John.saveSync(); console.log("saved!");

인스턴스 업데이트 및 저장은 단일 호출로 수행할 수 있습니다.

1 2 3
var John = Person.getSync(1); John.saveSync({ name: "Joe", surname: "Doe" }); console.log("saved!");

인스턴스를 제거하려면 다음을 수행하십시오.

1 2 3 4
// you could do this without even fetching it, look at Chaining section above var John = Person.getSync(1); John.removeSync(); console.log("removed!");

검증

Wiki 의 정보를 참조하세요 .

협회

연관은 하나 이상의 테이블 간의 관계입니다.

hasOne

다대일 관계 입니다 . 속한 것과 동일합니다 .
예: Animal.hasOne('owner', Person)동물
은 소유자가 한 명만 있을 수 있지만 사람은 여러 동물을 가질 수 있습니다.
동물에는 owner_id속성이 자동으로 추가됩니다.

다음 기능을 사용할 수 있게 됩니다:

1 2 3 4
animal.getOwnerSync() // Gets owner animal.setOwnerSync(person) // Sets owner_id animal.hasOwnerSync() // Checks if owner exists animal.removeOwnerSync() // Sets owner_id to 0

체인 찾기

hasOne 연결은 체인 찾기와도 호환됩니다. 위의 예를 사용하여 ChainFind 개체의 새 인스턴스에 액세스할 수 있습니다.

1
Animal.findByOwner({ /* options */ })

역방향 액세스

1
Animal.hasOne('owner', Person, {reverse: 'pets'})

다음을 추가합니다:

1 2 3 4 5 6
// Instance methods person.getPetsSync(function..) person.setPetsSync(cat, function..) // Model methods Person.findByPets({ /* options */ }) // returns ChainFind object

hasMany

다대다 관계 입니다 (조인 테이블 포함).
예: Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true })환자
는 다양한 의사를 가질 수 있습니다. 각 의사는 다양한 환자를 가질 수 있습니다.

patient_doctors다음을 호출하면 조인 테이블이 생성됩니다 Patient.sync().

열 이름 유형
환자_ID 정수(복합 키)
의사_ID 정수(복합 키)
varchar(255)

다음 기능을 사용할 수 있습니다.

1 2 3 4 5 6 7 8 9 10 11 12
patient.getDoctorsSync() // List of doctors patient.addDoctorsSync(docs) // Adds entries to join table patient.setDoctorsSync(docs) // Removes existing entries in join table, adds new ones patient.hasDoctorsSync(docs) // Checks if patient is associated to specified doctors patient.removeDoctorsSync(docs) // Removes specified doctors from join table doctor.getPatientsSync() etc... // You can also do: patient.doctors = [doc1, doc2]; patient.saveSync()

의사를 환자에 연결하려면:

1
patient.addDoctorSync(surgeon, {why: "remove appendix"})

{patient_id: 4, doctor_id: 6, why: "remove appendix"}조인 테이블에 추가됩니다 .

get접근자

이 유형의 연결에 있는 이 접근자는 ChainFind콜백을 전달하지 않으면 를 반환합니다. 즉, 다음과 같은 작업을 수행할 수 있습니다.

1 2
var doctors = patient.getDoctors().order("name").offset(1).runSync()); // ... all doctors, ordered by name, excluding first one

extendsTo

선택적 속성을 다른 테이블이나 컬렉션으로 분할하려는 경우 모든 확장은 각 행의 고유 식별자가 기본 모델 인스턴스 ID인 새 테이블에 있게 됩니다. 예를 들면 다음과 같습니다.

1 2 3 4 5 6 7
var Person = db.define("person", { name : String }); var PersonAddress = Person.extendsTo("address", { street : String, number : Number });

그러면 과 person열이 포함된 테이블이 생성됩니다 . 확장 프로그램은 , 열이 포함된 테이블을 생성합니다 . 모델에서 사용할 수 있는 메서드는 연결 과 유사합니다 . 이 예에서는 , , ..을 호출할 수 있습니다.idnameperson_addressperson_idstreetnumberPersonhasOne.getAddress(cb).setAddress(Address, cb)

참고: 의 결과를 저장할 필요는 없습니다 Person.extendsTo. 확장 모델을 반환합니다. 이를 사용하여 이 확장 테이블을 직접 쿼리하고 관련 모델을 찾을 수도 있지만 이는 사용자에게 달려 있습니다. 액세스만 원하는 경우 원래 모델을 사용하면 반품을 버릴 수 있습니다.

Examples & options

1과 n의 관계가 있는 경우 hasOne연관(속함)을 사용해야 합니다.

1 2 3 4 5 6 7 8 9 10 11 12 13
var Person = db.define('person', { name : String }); var Animal = db.define('animal', { name : String }); Animal.hasOne("owner", Person); // creates column 'owner_id' in 'animal' table // get animal with id = 123 var animal = Animal.getSync(123); // animal is the animal model instance, if found var person = animal.getOwnerSync(); // if animal has really an owner, person points to it

owner_id다음 옵션 을 지정하여 데이터베이스에서 해당 필드를 필수로 표시할 수 있습니다 required.

1
Animal.hasOne("owner", Person, { required: true });

필드가 필요하지 않지만 존재하지 않더라도 유효성을 검사해야 하는 경우 옵션을 지정합니다 alwaysValidate(예를 들어 Null 필드의 유효성 검사가 레코드의 다른 필드에 따라 달라지는 경우 발생할 수 있음).

1
Animal.hasOne("owner", Person, { required: false, alwaysValidate: true });

필드(owner_id)에 다른 이름을 사용하려는 경우 설정에서 이 매개변수를 변경할 수 있습니다.

1
db.settings.set("properties.association_key", "{field}_{name}"); // {name} will be replaced by 'owner' and {field} will be replaced by 'id' in this case

참고: 이 작업은 연결을 지정하기 전에 수행되어야 합니다.

연결 hasMany은 연결 테이블에 추가 속성을 가질 수 있습니다.

1 2 3 4 5 6 7 8 9 10 11
var Person = db.define('person', { name : String }); Person.hasMany("friends", { rate : Number }, {}, { key: true }); var John = Person.getSync(123); var friends = John.getFriendsSync(); // assumes rate is another column on table person_friends // you can access it by going to friends[N].extra.rate

원하는 경우 을(를) 활성화할 수 있습니다 autoFetch. 이렇게 하면 모델 인스턴스를 가져오거나 찾을 때 연결이 자동으로 가져옵니다.

1 2 3 4 5 6 7 8 9 10 11 12
var Person = db.define('person', { name : String }); Person.hasMany("friends", { rate : Number }, { key : true, // Turns the foreign keys in the join table into a composite key autoFetch : true }); var John = Person.getSync(123); // no need to do John.getFriends() , John already has John.friends Array

연결별로 기준을 정하는 대신 전역적으로 이 옵션을 정의할 수도 있습니다.

1 2 3 4 5 6 7 8 9 10
var Person = db.define('person', { name : String }, { autoFetch : true }); Person.hasMany("friends", { rate : Number }, { key: true });

연관은 옵션을 사용하여 연관된 모델을 호출할 수 있습니다 reverse. 예를 들어, ModelA에서 ModelB로의 연관이 있는 경우 ModelB에서 접근자를 생성하여 ModelA에서 인스턴스를 가져올 수 있습니다. 혼란스럽습니까? 다음 예를 살펴보십시오.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var Pet = db.define('pet', { name : String }); var Person = db.define('person', { name : String }); Pet.hasOne("owner", Person, { reverse : "pets" }); var pets = Person(4).getPetsSync(); // although the association was made on Pet, // Person will have an accessor (getPets) // // In this example, ORM will fetch all pets // whose owner_id = 4

이는 양쪽에서 다대다hasMany 연결 을 관리할 수 있으므로 연결이 있을 때 더욱 의미가 있습니다 .

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var Pet = db.define('pet', { name : String }); var Person = db.define('person', { name : String }); Person.hasMany("pets", Pet, { bought : Date }, { key : true, reverse : "owners" }); Person(1).getPetsSync(...); Pet(2).getOwnersSync(...);

거래 지원

낮은 수준의 트랜잭션 기능을 사용하여 DB 트랜잭션을 처리할 수 있습니다.

1 2 3 4 5 6
db.begin(); ... if(err) db.rollback(); else db.commit();

또는 trans를 사용하여 간단하게 처리할 수도 있습니다.

1 2 3 4
var result = db.trans(() => { ... return result; });

외부 데이터베이스 어댑터 추가

에 외부 데이터베이스 어댑터를 추가하려면 메소드를 orm호출하고 addAdapter어댑터 생성자와 함께 이 어댑터와 연결하는 데 사용할 별칭을 전달합니다.

1
require('orm').addAdapter('cassandra', CassandraAdapter);

보다the documentation for creating adapters상세 사항은.