React Native
...
Data objects
Relational Queries
9 분
파스(parse)를 이용한 리액트 네이티브의 관계형 쿼리 소개 이 가이드에서는 파스에서 관계형 쿼리를 수행하고 이러한 쿼리를 사용하여 리액트 네이티브 컴포넌트를 구현합니다 back4app과 리액트 네이티브를 사용하여 현실적인 데이터를 설정하고 쿼리하는 방법을 배웁니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 리액트 네이티브 앱이 생성되어 back4app 에 연결되어 있어야 합니다 이 가이드에서 제공하는 화면 레이아웃을 테스트/사용하려면 react native paper react native paper 를 설정해야 합니다 라이브러리 목표 리액트 네이티브 앱에서 back4app에 저장된 관계형 데이터를 쿼리합니다 1 parse query 클래스 이해하기 모든 parse 쿼리 작업은 parse query parse query 객체 유형을 사용하며, 이는 앱 전반에 걸쳐 데이터베이스에서 특정 데이터를 검색하는 데 도움이 됩니다 parse query parse query 는 검색 메서드(예 parse query find parse query find 또는 parse query first parse query first 호출 후에만 해결된다는 것을 아는 것이 중요합니다 따라서 쿼리를 설정하고 실제로 호출되기 전에 여러 수정자를 연결할 수 있습니다 새로운 parse query parse query , 생성하려면 원하는 parse object parse object 하위 클래스를 매개변수로 전달해야 하며, 이는 쿼리 결과를 포함할 것입니다 아래에서 볼 수 있는 예제 쿼리에서는 가상의 book book 하위 클래스가 쿼리되고 있습니다 1 // this will create your query 2 let parsequery = new parse query("book"); 3 // the query will resolve only after calling this method 4 let queryresult = await parsequery find(); 다음에 대한 자세한 내용을 읽을 수 있습니다 parse query parse query 클래스는 공식 문서에서 여기 https //parseplatform org/parse sdk js/api/master/parse query html 2 back4app에 데이터 저장하기 이 가이드에서 쿼리의 대상이 될 다양한 클래스를 생성해 보겠습니다 클래스는 다음과 같습니다 저자 저자 , 책 책 , 출판사 출판사 및 서점 서점 , 여기서 책 책 은 출판사 출판사 와 1\ n 관계를 가지며 저자 저자 와 n\ n 관계를 가집니다 그리고 서점 서점 은 책 책 과 n\ n 관계를 가집니다 parse js 콘솔에서는 javascript 코드를 직접 실행하여 js sdk 명령을 사용하여 애플리케이션 데이터베이스 내용을 쿼리하고 업데이트할 수 있습니다 아래 코드를 js 콘솔에서 실행하고 back4app에 데이터를 삽입하세요 대시보드에서 js 콘솔은 다음과 같이 보입니다 계속 진행하여 다음 예제 내용을 사용하여 클래스를 생성하세요 1 // add objects and create tables 2 // authors 3 const authora = new parse object('author'); 4 authora set('name', 'aaron writer'); 5 await authora save(); 6	 7 const authorb = new parse object('author'); 8 authorb set('name', 'beatrice novelist'); 9 await authorb save(); 10	 11 const authorc = new parse object('author'); 12 authorc set('name', 'casey columnist'); 13 await authorc save(); 14	 15 // publishers 16 const publishera = new parse object('publisher'); 17 publishera set('name', 'acacia publishings'); 18 await publishera save(); 19	 20 const publisherb = new parse object('publisher'); 21 publisherb set('name', 'birch distributions'); 22 await publisherb save(); 23	 24 // books 25 const booka = new parse object('book'); 26 booka set('title', 'a love story'); 27 booka set('publisher', publishera); 28 booka set('publishingdate', new date('05/07/1998')); 29 const bookarelation = booka relation("authors"); 30 bookarelation add(authora); 31 await booka save(); 32	 33 const bookb = new parse object('book'); 34 bookb set('title', 'benevolent elves'); 35 bookb set('publisher', publisherb); 36 bookb set('publishingdate', new date('11/31/2008')); 37 const bookbrelation = bookb relation("authors"); 38 bookbrelation add(authorb); 39 await bookb save(); 40	 41 const bookc = new parse object('book'); 42 bookc set('title', 'can you believe it?'); 43 bookc set('publisher', publisherb); 44 bookc set('publishingdate', new date('08/21/2018')); 45 const bookcrelation = bookc relation("authors"); 46 bookcrelation add(authora); 47 bookcrelation add(authorc); 48 await bookc save(); 49	 50 // bookstore 51 const bookstorea = new parse object('bookstore'); 52 bookstorea set('name', 'books of love'); 53 const bookstorearelation = bookstorea relation("books"); 54 bookstorearelation add(booka); 55 await bookstorea save(); 56	 57 const bookstoreb = new parse object('bookstore'); 58 bookstoreb set('name', 'fantasy books'); 59 const bookstorebrelation = bookstoreb relation("books"); 60 bookstorebrelation add(bookb); 61 await bookstoreb save(); 62	 63 const bookstorec = new parse object('bookstore'); 64 bookstorec set('name', 'general books'); 65 const bookstorecrelation = bookstorec relation("books"); 66 bookstorecrelation add(booka); 67 bookstorecrelation add(bookc); 68 await bookstorec save(); 69	 70 console log('success'); 3 데이터 쿼리 모든 클래스를 채웠으니, 이제 그 안에서 몇 가지 관계형 쿼리를 수행할 수 있습니다 출판사로 결과를 필터링하는 것부터 시작해 보겠습니다 책 책 의 결과를 찾고, 출판사 출판사 “acacia publishings” (또는 “출판사 a”)에 속하는 것을 찾기 위해 기본 parse query equalto parse query equalto 메서드를 사용합니다 1 // get publishera object 2 const publisheraquery = new parse query('publisher'); 3 publisheraquery equalto('name', 'acacia publishings'); 4 const publishera = await publisheraquery first(); 5	 6 // query books with publishera 7 const bookquery = new parse query('book'); 8 bookquery equalto('publisher', publishera); 9 let queryresults = await bookquery find(); 10	 11 // let's show the results 12 for (let result of queryresults) { 13 // you access `parse objects` attributes by using ` get` 14 console log(result get('title')); 15 }; 이제 bookstore bookstore 객체가 book book 객체를 포함하고 있는지 쿼리해 보겠습니다 출판 날짜가 2010년 1월 1일 이후인 객체를 찾기 위해 parse query greaterthan parse query greaterthan 메서드와 parse query matchesquery parse query matchesquery 메서드를 사용합니다 1 // create inner book query 2 const bookquery = new parse query('book'); 3 bookquery greaterthan('publishingdate', new date('01/01/2010')); 4	 5 // query bookstore using inner book query 6 const bookstorequery = new parse query('bookstore'); 7 bookstorequery matchesquery('books', bookquery); 8 let queryresults = await bookstorequery find(); 9	 10 // let's show the results 11 for (let result of queryresults) { 12 // you access `parse objects` attributes by using ` get` 13 console log(result get('name')); 14 }; 이제 bookstore bookstore 객체를 더 복잡한 관계 쿼리로 생성해 보겠습니다 book book 객체가 최소한 하나의 author author “aaron writer” (또는 “authora”)에 의해 작성된 객체를 찾기 위해 equalto equalto 및 matchesquery matchesquery 1 // get authora object 2 const authoraquery = new parse query('author'); 3 authoraquery equalto('name', 'aaron writer'); 4 const authora = await authoraquery first(); 5	 6 // create inner book query 7 const bookquery = new parse query('book'); 8 bookquery equalto('authors', authora); 9	 10 // query bookstore using inner book query 11 const bookstorequery = new parse query('bookstore'); 12 bookstorequery matchesquery('books', bookquery); 13 let queryresults = await bookstorequery find(); 14	 15 // let's show the results 16 for (let result of queryresults) { 17 // you access `parse objects` attributes by using ` get` 18 console log(result get('name')); 19 }; 4 리액트 네이티브 컴포넌트에서 쿼리하기 이제 react native의 구성 요소 내에서 예제 쿼리를 사용해 보겠습니다 결과를 보여주는 목록과 쿼리를 호출하는 버튼이 있는 간단한 인터페이스를 가지고 있습니다 구성 요소 코드는 다음과 같이 배치되어 있으며, doquery doquery 함수가 포함되어 있습니다 이전의 예제 코드가 포함되어 있습니다 javascript 1 import react, {usestate} from 'react'; 2 import {alert, image, view, scrollview, stylesheet} from 'react native'; 3 import parse from 'parse/react native'; 4 import { 5 list, 6 title, 7 button as paperbutton, 8 text as papertext, 9 } from 'react native paper'; 10	 11 export const querylist = () => { 12 // state variable 13 const \[queryresults, setqueryresults] = usestate(null); 14	 15 const doquerya = async function () { 16 // get publishera object 17 const publisheraquery = new parse query('publisher'); 18 publisheraquery equalto('name', 'acacia publishings'); 19 const publishera = await publisheraquery first(); 20	 21 // query books with publishera 22 const bookquery = new parse query('book'); 23 bookquery equalto('publisher', publishera); 24	 25 try { 26 let results = await bookquery find(); 27 setqueryresults(results); 28 return true; 29 } catch (error) { 30 // error can be caused by lack of internet connection 31 alert alert('error!', error message); 32 return false; 33 } 34 }; 35	 36 const doqueryb = async function () { 37 // create inner book query 38 const bookquery = new parse query('book'); 39 bookquery greaterthan('publishingdate', new date('01/01/2010')); 40	 41 // query bookstore using inner book query 42 const bookstorequery = new parse query('bookstore'); 43 bookstorequery matchesquery('books', bookquery); 44	 45 try { 46 let results = await bookstorequery find(); 47 setqueryresults(results); 48 return true; 49 } catch (error) { 50 // error can be caused by lack of internet connection 51 alert alert('error!', error message); 52 return false; 53 } 54 }; 55	 56 const doqueryc = async function () { 57 // get authora object 58 const authoraquery = new parse query('author'); 59 authoraquery equalto('name', 'aaron writer'); 60 const authora = await authoraquery first(); 61	 62 // create inner book query 63 const bookquery = new parse query('book'); 64 bookquery equalto('authors', authora); 65	 66 // query bookstore using inner book query 67 const bookstorequery = new parse query('bookstore'); 68 bookstorequery matchesquery('books', bookquery); 69	 70 try { 71 let results = await bookstorequery find(); 72 setqueryresults(results); 73 return true; 74 } catch (error) { 75 // error can be caused by lack of internet connection 76 alert alert('error!', error message); 77 return false; 78 } 79 }; 80	 81 const clearqueryresults = async function () { 82 setqueryresults(null); 83 return true; 84 }; 85	 86 return ( 87 <> 88 \<view style={styles header}> 89 \<image 90 style={styles header logo} 91 source={ { 92 uri 93 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 94 } } 95 /> 96 \<papertext style={styles header text}> 97 \<papertext style={styles header text bold}> 98 {'react native on back4app '} 99 \</papertext> 100 {' relational queries'} 101 \</papertext> 102 \</view> 103 \<scrollview style={styles wrapper}> 104 \<view> 105 \<title>{'result list'}\</title> 106 {/ query list /} 107 {queryresults !== null && 108 queryresults !== undefined && 109 queryresults map((result) => ( 110 \<list item 111 key={result id} 112 title={ 113 result get('name') !== undefined 114 ? result get('name') 115 result get('title') 116 } 117 titlestyle={styles list text} 118 style={styles list item} 119 /> 120 ))} 121 {queryresults === null || 122 queryresults === undefined || 123 (queryresults !== null && 124 queryresults !== undefined && 125 queryresults length <= 0) ? ( 126 \<papertext>{'no results here!'}\</papertext> 127 ) null} 128 \</view> 129 \<view> 130 \<title>{'query buttons'}\</title> 131 \<paperbutton 132 onpress={() => doquerya()} 133 mode="contained" 134 icon="search web" 135 color={'#208aec'} 136 style={styles list button}> 137 {'query a'} 138 \</paperbutton> 139 \<paperbutton 140 onpress={() => doqueryb()} 141 mode="contained" 142 icon="search web" 143 color={'#208aec'} 144 style={styles list button}> 145 {'query b'} 146 \</paperbutton> 147 \<paperbutton 148 onpress={() => doqueryc()} 149 mode="contained" 150 icon="search web" 151 color={'#208aec'} 152 style={styles list button}> 153 {'query c'} 154 \</paperbutton> 155 \<paperbutton 156 onpress={() => clearqueryresults()} 157 mode="contained" 158 icon="delete" 159 color={'#208aec'} 160 style={styles list button}> 161 {'clear results'} 162 \</paperbutton> 163 \</view> 164 \</scrollview> 165 \</> 166 ); 167 }; 168	 169 // these define the screen component styles 170 const styles = stylesheet create({ 171 header { 172 alignitems 'center', 173 paddingtop 30, 174 paddingbottom 50, 175 backgroundcolor '#208aec', 176 }, 177 header logo { 178 height 50, 179 width 220, 180 resizemode 'contain', 181 }, 182 header text { 183 margintop 15, 184 color '#f0f0f0', 185 fontsize 16, 186 }, 187 header text bold { 188 color '#fff', 189 fontweight 'bold', 190 }, 191 wrapper { 192 width '90%', 193 alignself 'center', 194 }, 195 list button { 196 margintop 6, 197 marginleft 15, 198 height 40, 199 }, 200 list item { 201 borderbottomwidth 1, 202 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 203 }, 204 list text { 205 fontsize 15, 206 }, 207 });1 import react, {fc, reactelement, usestate} from 'react'; 2 import {alert, image, view, scrollview, stylesheet} from 'react native'; 3 import parse from 'parse/react native'; 4 import { 5 list, 6 title, 7 button as paperbutton, 8 text as papertext, 9 } from 'react native paper'; 10	 11 export const querylist fc<{}> = ({}) reactelement => { 12 // state variable 13 const \[queryresults, setqueryresults] = usestate(null); 14	 15 const doquerya = async function () promise\<boolean> { 16 // get publishera object 17 const publisheraquery parse query = new parse query('publisher'); 18 publisheraquery equalto('name', 'acacia publishings'); 19 const publishera parse object = await publisheraquery first(); 20	 21 // query books with publishera 22 const bookquery parse query = new parse query('book'); 23 bookquery equalto('publisher', publishera); 24	 25 try { 26 let results \[parse object] = await bookquery find(); 27 setqueryresults(results); 28 return true; 29 } catch (error) { 30 // error can be caused by lack of internet connection 31 alert alert('error!', error message); 32 return false; 33 } 34 }; 35	 36 const doqueryb = async function () promise\<boolean> { 37 // create inner book query 38 const bookquery parse query = new parse query('book'); 39 bookquery greaterthan('publishingdate', new date('01/01/2010')); 40	 41 // query bookstore using inner book query 42 const bookstorequery parse query = new parse query('bookstore'); 43 bookstorequery matchesquery('books', bookquery); 44	 45 try { 46 let results \[parse object] = await bookstorequery find(); 47 setqueryresults(results); 48 return true; 49 } catch (error) { 50 // error can be caused by lack of internet connection 51 alert alert('error!', error message); 52 return false; 53 } 54 }; 55	 56 const doqueryc = async function () promise\<boolean> { 57 // get authora object 58 const authoraquery parse query = new parse query('author'); 59 authoraquery equalto('name', 'aaron writer'); 60 const authora parse object = await authoraquery first(); 61	 62 // create inner book query 63 const bookquery parse query = new parse query('book'); 64 bookquery equalto('authors', authora); 65	 66 // query bookstore using inner book query 67 const bookstorequery parse query = new parse query('bookstore'); 68 bookstorequery matchesquery('books', bookquery); 69	 70 try { 71 let results \[parse object] = await bookstorequery find(); 72 setqueryresults(results); 73 return true; 74 } catch (error) { 75 // error can be caused by lack of internet connection 76 alert alert('error!', error message); 77 return false; 78 } 79 }; 80	 81 const clearqueryresults = async function () promise\<boolean> { 82 setqueryresults(null); 83 return true; 84 }; 85	 86 return ( 87 <> 88 \<view style={styles header}> 89 \<image 90 style={styles header logo} 91 source={ { 92 uri 93 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 94 } } 95 /> 96 \<papertext style={styles header text}> 97 \<papertext style={styles header text bold}> 98 {'react native on back4app '} 99 \</papertext> 100 {' relational queries'} 101 \</papertext> 102 \</view> 103 \<scrollview style={styles wrapper}> 104 \<view> 105 \<title>{'result list'}\</title> 106 {/ query list /} 107 {queryresults !== null && 108 queryresults !== undefined && 109 queryresults map((result parse object) => ( 110 \<list item 111 key={result id} 112 title={ 113 result get('name') !== undefined 114 ? result get('name') 115 result get('title') 116 } 117 titlestyle={styles list text} 118 style={styles list item} 119 /> 120 ))} 121 {queryresults === null || 122 queryresults === undefined || 123 (queryresults !== null && 124 queryresults !== undefined && 125 queryresults length <= 0) ? ( 126 \<papertext>{'no results here!'}\</papertext> 127 ) null} 128 \</view> 129 \<view> 130 \<title>{'query buttons'}\</title> 131 \<paperbutton 132 onpress={() => doquerya()} 133 mode="contained" 134 icon="search web" 135 color={'#208aec'} 136 style={styles list button}> 137 {'query a'} 138 \</paperbutton> 139 \<paperbutton 140 onpress={() => doqueryb()} 141 mode="contained" 142 icon="search web" 143 color={'#208aec'} 144 style={styles list button}> 145 {'query b'} 146 \</paperbutton> 147 \<paperbutton 148 onpress={() => doqueryc()} 149 mode="contained" 150 icon="search web" 151 color={'#208aec'} 152 style={styles list button}> 153 {'query c'} 154 \</paperbutton> 155 \<paperbutton 156 onpress={() => clearqueryresults()} 157 mode="contained" 158 icon="delete" 159 color={'#208aec'} 160 style={styles list button}> 161 {'clear results'} 162 \</paperbutton> 163 \</view> 164 \</scrollview> 165 \</> 166 ); 167 }; 168	 169 // these define the screen component styles 170 const styles = stylesheet create({ 171 header { 172 alignitems 'center', 173 paddingtop 30, 174 paddingbottom 50, 175 backgroundcolor '#208aec', 176 }, 177 header logo { 178 height 50, 179 width 220, 180 resizemode 'contain', 181 }, 182 header text { 183 margintop 15, 184 color '#f0f0f0', 185 fontsize 16, 186 }, 187 header text bold { 188 color '#fff', 189 fontweight 'bold', 190 }, 191 wrapper { 192 width '90%', 193 alignself 'center', 194 }, 195 list button { 196 margintop 6, 197 marginleft 15, 198 height 40, 199 }, 200 list item { 201 borderbottomwidth 1, 202 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 203 }, 204 list text { 205 fontsize 15, 206 }, 207 }); 렌더링 및 쿼리 함수 중 하나로 쿼리한 후 컴포넌트가 어떻게 보여야 하는지입니다 결론 이 가이드를 마치면서, parse에서 관계형 쿼리가 어떻게 작동하는지와 react native 앱에서 back4app으로 이를 수행하는 방법을 배웠습니다 다음 가이드에서는 parse에서 사용자와 작업하는 방법을 배울 것입니다