Javascript/Node.js

[Objection.js] Eager Loading Method

Frankie 2021. 9. 9. 16:43

withGraphFetched(), withGraphJoined() - 모든 쿼리의 결과에 대한 관련 항목의 그래프를 가져온다. 

withGraphFetched() - 후드 아래에서 여러 쿼리를 사용하여 결과를 가져온다.

 

* eager loading: 요청 받으면 모든 것을 한다. 예로 두 행렬을 곱하는 것이 있다. 모든 계산을 하는 것이다.


// '아놀드'라는 이름을 가진 사람과 그들의 모든 애완동물들을 가져온다.

const people = await Person.query()
	.where('fristName', 'Arnold')
	.withGraphFetched('pets');


// 각 결과에 대한 자식 관계를 가져오고 그에 관계된 애완동물과 영화에 대한 관계 가져온다.

const people = await Person.query()
	.withGraphFetched('children.[pets, movies]');


// modifier 함수로 관계 결과를 필터링하고 수정할 수 있다.

const people = await Person.query()
	.withGraphFethced('children(selectNameAndId)'.[pets(onlyDogs, orderByName), movies]')
	.modifiers({
		selectNameAndId(builder){
			builder.select('name','id');
		},
		orderByName(builder){
			builder.orderBy('name');
		},
		onlyDogs(builder){
			builder.where('species', 'dog');
		}
	});

->  modifiers를 사용하는 모델 클래스에 대해서

 

// 필터링은 modifyGraph 함수를 사용해서 할 수도 있다.

const people = await Person.query()
  .withGraphFetched('children.[pets, movies]')
  .modifyGraph('children', builder => {
    // Order children by age and only select id.
    builder.orderBy('age').select('id');
  })
  .modifyGraph('children.[pets, movies]', builder => {
    // Only select `pets` and `movies` whose id > 10 for the children.
    builder.where('id', '>', 10);
  });

 

withGraphJoined() - 단일 쿼리 및 조인을 사용하여 결과를 가져온다.

queryBuilder = queryBuilder.withGraphJoined(relationExpression, graphOptions);

이 방법은 sql 조인을 사용하여 관계표현에 정의된 모든 관계를 조인한 다음 GraphFetched로 얻은 것과 동일한 모델 인스턴스의 그래프로 결과를 구문 분석한다. 이 방법의 주요 이점은 관계를 기준으로 쿼리를 필터링할 수 있다는 것이다.

 

기본적으로 레프트 조인이 사용되지만 joinOpertaion 옵션을 사용하여 조인 유형을 정의할 수 있다.

 

GraphJoined와 함께 사용하면 모든 관계가 기본 쿼리에 결합되며 쿼리 작성 방법에 참조할 수 있다. 중첩된 관계는 :를 구분 기호로 사용하여 관계 이름을 연결하여 명명된다.

const people = await Person.query()
  .withGraphJoined('children.[pets, movies]')
  .whereIn('children.firstName', ['Arnold', 'Jennifer'])
  .where('children:pets.name', 'Fluffy')
  .where('children:movies.name', 'like', 'Terminator%');

 

allowGraph() - GraphFetched, GraphJoined, insertGraph, upsertGraph 메서드를 사용할 때 관계 트리를 설정한다.

 

GraphFetched 또는 GraphJoined와 함께 사용할 경우 쿼리가 거절되고, 메서드에 전달된 식이 allowGraph의 하위 집합이 아닌 경우 오류가 발생한다. 이 함수는 관계식이 http 요청의 쿼리 매개 변수와 같이 신뢰할 수 없는 경로에서 온 경우 유용합니다.

 

예) actors가 허용되지 않아서 쿼리가 거절된다.

await Person.query()
  .allowGraph('[children.pets, movies]')
  .withGraphFetched('movies.actors');

예) 정상적으로 작동

await Person.query()
  .allowGraph('[children.pets, movies]')
  .withGraphFetched('children.pets');

예) allowGraph를 여러 번 부르면 표현식들을 합친다.

await Person.query()
  .allowGraph('children.pets')
  .allowGraph('movies')
  .withGraphFetched(req.query.eager);

예) insertGraph와 upsertGraph 사용도 마찬가지다.

const insertedPerson = await Person.query()
  .allowGraph('[children.pets, movies]')
  .insertGraph({
    firstName: 'Sylvester',
    children: [
      {
        firstName: 'Sage',
        pets: [
          {
            name: 'Fluffy',
            species: 'dog'
          },
          {
            name: 'Scrappy',
            species: 'dog'
          }
        ]
      }
    ]
  });

예) cousins는 허용되지 않는다

const insertedPerson = await Person.query()
  .allowGraph('[children.pets, movies]')
  .upsertGraph({
    firstName: 'Sylvester',

    children: [
      {
        firstName: 'Sage',
        pets: [
          {
            name: 'Fluffy',
            species: 'dog'
          },
          {
            name: 'Scrappy',
            species: 'dog'
          }
        ]
      }
    ],

    cousins: [sylvestersCousin]
  });

'Javascript > Node.js' 카테고리의 다른 글

[Node.js] 2. 에러 처리 방법  (0) 2021.09.10
1. 프로젝트 구조 설계  (0) 2021.09.10
옵셔널 체이닝 - '?.'  (0) 2021.09.02
[Node.js] 개념  (0) 2021.07.20
[Node.js] 자바스크립트 런타임  (0) 2021.07.19