Flutter
...
Data Queries
플러터에서 Parse 관계형 데이터 쿼리 구현
11 분
플러터에서 관계형 쿼리 파싱하기 소개 당신은 이미 관계형 데이터 객체를 저장하는 방법 을 보았습니다 parse pointer 및 parse relations 데이터 유형을 사용하여 parse에서는 다른 parseobject의 값으로 어떤 parseobject도 사용할 수 있다는 것을 배웠습니다 이를 통해 두 객체 간의 관계를 설정할 수 있습니다 내부적으로 parse 프레임워크는 일관성을 유지하기 위해 참조된 객체를 한 곳에 저장합니다 이는 복잡한 쿼리를 구축하고 실행할 때 추가적인 힘을 줄 수 있습니다 또한, 당신은 이미 querybuilder를 사용하는 방법 을 배웠습니다 get을 사용하면 back4app에서 단일 parseobject를 검색할 수 있습니다 querybuilder를 사용하여 데이터를 검색하는 다른 많은 방법이 있습니다 이 가이드에서는 querybuilder 클래스에 대해 깊이 파고들고 관계형 쿼리를 구축하는 데 사용할 수 있는 메서드를 살펴볼 것입니다 간단한 데이터베이스 클래스를 사용하여 일부 모의 데이터를 사용하여 back4app에서 flutter를 사용하여 쿼리를 수행할 것입니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 android studio https //developer android com/studio 또는 vs code 설치 (이와 함께 플러그인 dart 및 flutter) back4app에서 생성된 앱 참고 back4app에서 parse app을 만드는 방법을 배우려면 새 parse app 튜토리얼 을 따르세요 back4app에 연결된 flutter 앱 참고 back4app에 연결된 flutter 프로젝트를 만들려면 flutter 프로젝트에 parse sdk 설치 을 따르세요 android 또는 ios를 실행하는 장치(또는 가상 장치) 목표 flutter 앱에서 back4app에 저장된 관계형 데이터 쿼리 1 querybuilder 클래스 이해하기 모든 parse 쿼리 작업은 querybuilder 객체 유형을 사용하며, 이를 통해 앱 전반에 걸쳐 데이터베이스에서 특정 데이터를 검색할 수 있습니다 새 querybuilder를 만들려면 원하는 parseobject 하위 클래스를 매개변수로 전달해야 하며, 이는 쿼리 결과를 포함할 것입니다 쿼리 빌더는 retrieve 메서드 쿼리를 호출한 후에만 해결된다는 것을 아는 것이 중요합니다 따라서 쿼리를 설정하고 실제로 호출되기 전에 여러 수정자를 연결할 수 있습니다 1 // this will create your query 2 querybuilder\<parseobject> querybook = 3 querybuilder\<parseobject>(parseobject('book')); 4 5 // the query will resolve only after calling this method 6 final parseresponse apiresponse = await querybook query(); 7	 8 if (apiresponse success && apiresponse results != null) { 9 10 } else { 11 12 } querybuilder 클래스에 대해 더 읽어보실 수 있습니다 여기에서 공식 문서 back4app에서 javascript 콘솔 사용하기 back4app 애플리케이션 대시보드 내에서 javascript 코드를 직접 실행할 수 있는 매우 유용한 api 콘솔을 찾을 수 있습니다 이 가이드를 사용하여 back4app에 데이터 객체를 저장할 것입니다 앱의 주요 대시보드에서 core >api console >javascript로 이동하세요 2 back4app에 데이터 저장하기 이 가이드에서 쿼리를 실행하려면 먼저 앱에 데이터를 채워야 합니다 클래스는 다음과 같습니다 author , book , publisher 및 bookstore 어떤 book 은 1\ n 관계를 가지고 있으며 publisher 와 n\ n 관계를 가지고 있습니다 그리고 bookstore 는 book과 n\ n 관계를 가지고 있습니다 여기 parse object 클래스 생성 코드가 있습니다 api 콘솔에서 실행해 보세요 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 const authord = new parse object('author'); 16 authord set('name', 'gary stur'); 17 await authord save(); 18 19 const authore = new parse object('author'); 20 authore set('name', 'mary sue'); 21 await authore save(); 22 23 // publishers 24 const publishera = new parse object('publisher'); 25 publishera set('name', 'acacia publishings'); 26 await publishera save(); 27 28 const publisherb = new parse object('publisher'); 29 publisherb set('name', 'birch distributions'); 30 await publisherb save(); 31 32 const publisherc = new parse object('publisher'); 33 publisherc set('name', 'acacia distributions'); 34 await publisherc save(); 35 36 37 // books 38 const booka = new parse object('book'); 39 booka set('title', 'a love story'); 40 booka set('publisher', publishera); 41 booka set('publishingdate', new date('05/07/1998')); 42 const bookarelation = booka relation("authors"); 43 bookarelation add(authora); 44 await booka save(); 45 46 const bookb = new parse object('book'); 47 bookb set('title', 'benevolent elves'); 48 bookb set('publisher', publisherb); 49 bookb set('publishingdate', new date('11/31/2008')); 50 const bookbrelation = bookb relation("authors"); 51 bookbrelation add(authorb); 52 await bookb save(); 53 54 const bookc = new parse object('book'); 55 bookc set('title', 'can you believe it?'); 56 bookc set('publisher', publisherb); 57 bookc set('publishingdate', new date('08/21/2018')); 58 const bookcrelation = bookc relation("authors"); 59 bookcrelation add(authora); 60 bookcrelation add(authorc); 61 await bookc save(); 62 63 // bookstore 64 const bookstorea = new parse object('bookstore'); 65 bookstorea set('name', 'books of love'); 66 const bookstorearelation = bookstorea relation("books"); 67 bookstorearelation add(booka); 68 await bookstorea save(); 69 70 const bookstoreb = new parse object('bookstore'); 71 bookstoreb set('name', 'fantasy books'); 72 const bookstorebrelation = bookstoreb relation("books"); 73 bookstorebrelation add(bookb); 74 await bookstoreb save(); 75 76 const bookstorec = new parse object('bookstore'); 77 bookstorec set('name', 'general books'); 78 const bookstorecrelation = bookstorec relation("books"); 79 bookstorecrelation add(booka); 80 bookstorecrelation add(bookc); 81 await bookstorec save(); 82 83 console log('success'); 이 코드를 실행한 후, 데이터베이스에 author, publisher, book 및 bookstore 클래스가 생성되어야 합니다 당신의 새로운 클래스는 다음과 같아야 합니다 이제 모든 querybuilder 메서드의 예를 살펴보고, 그들이 하는 일에 대한 간단한 설명을 추가하겠습니다 3 데이터 쿼리하기 이제 클래스가 채워졌으므로, 몇 가지 관계형 쿼리를 수행할 수 있습니다 모든 클래스가 채워졌으므로, 이제 그 안에서 몇 가지 관계형 쿼리를 수행할 수 있습니다 출판사로 책 결과를 필터링하는 것부터 시작하겠습니다 “acacia publishings” (또는 “publisher a”)에 속하는 것을 기본 whereequalto 메서드를 사용하여 관계형 포인터로 검색합니다 1 // get publishera object 2 final querybuilder\<parseobject> publisherquerya = 3 querybuilder\<parseobject>(parseobject('publisher')) 4 whereequalto('name', 'acacia publishings'); 5 6 final parseresponse publisherresponse = await publisherquerya query(); 7 if (!publisherresponse success) { 8 return; 9 } 10 final publishera = publisherresponse results? first as parseobject; 11 12 // query books with publishera 13 final querybuilder\<parseobject> bookquery = 14 querybuilder\<parseobject>(parseobject('book')) 15 whereequalto('publisher', publishera); 16 17 final parseresponse bookresponse = await bookquery query(); 18 if (!bookresponse success) { 19 return; 20 } 21 22 for (var book in bookresponse results as list\<parseobject>) { 23 print(book get('title')); 24 } 이제 출판 날짜가 2010년 1월 1일 이후인 책 객체를 포함하는 bookstore 객체를 쿼리해 보겠습니다 wheregreaterthan 메서드와 그 다음에 wherematchesquery 메서드를 사용하여 내부 쿼리를 수행합니다 1 // create inner book query 2 final querybuilder\<parseobject> bookquery = 3 querybuilder\<parseobject>(parseobject('book')) 4 wheregreaterthan('publishingdate', datetime(2010, 01, 01)); 5 6 // query bookstore using inner book query 7 final querybuilder\<parseobject> bookstorequery = 8 querybuilder\<parseobject>(parseobject('bookstore')) 9 wherematchesquery('books', bookquery); 10 11 final parseresponse bookstoreresponse = await bookstorequery query(); 12 if (!bookstoreresponse success) { 13 return; 14 } 15 16 for (var b in bookstoreresponse results as list\<parseobject>) { 17 print(b get('name')); 18 } 이제 책과 관련된 저자를 찾는 또 다른 쿼리를 생성해 보겠습니다 can you believe it ?, whererelatedto를 사용하여 1 // get book object 2 final querybuilder\<parseobject> bookquery = 3 querybuilder\<parseobject>(parseobject('book')) 4 whereequalto('title', 'can you believe it?'); 5 6 final parseresponse bookresponse = await bookquery query(); 7 if (!bookresponse success) { 8 return; 9 } 10 11 final book = bookresponse results? first as parseobject; 12 13 // get author with relation with book can you believe it? 14 final querybuilder\<parseobject> authorsquery = 15 querybuilder\<parseobject>(parseobject('author')) 16 whererelatedto('authors', 'book', book objectid!); 17 18 final parseresponse authorresponse = await authorsquery query(); 19 20 // let's show the results 21 if (authorresponse success && authorresponse results != null) { 22 for (var a in authorresponse results! as list\<parseobject>) { 23 print(a get('name')); 24 } 25 } 4 flutter에서의 쿼리 이제 flutter 앱 내에서 예제 쿼리를 사용해 보겠습니다 결과를 보여주는 목록과 쿼리를 호출하는 3개의 버튼이 있는 간단한 인터페이스를 갖추고 있습니다 flutter 프로젝트를 열고, main dart 파일로 이동하여 모든 코드를 정리하고 다음으로 교체하세요 1 import 'package\ flutter/cupertino dart'; 2 import 'package\ flutter/material dart'; 3 import 'package\ parse server sdk flutter/parse server sdk dart'; 4 5 void main() async { 6 widgetsflutterbinding ensureinitialized(); 7 8 final keyapplicationid = 'your app id here'; 9 final keyclientkey = 'your client key here'; 10 final keyparseserverurl = 'https //parseapi back4app com'; 11 12 await parse() initialize(keyapplicationid, keyparseserverurl, 13 clientkey keyclientkey, debug true); 14 15 runapp(materialapp( 16 title 'flutter geopoint', 17 debugshowcheckedmodebanner false, 18 home homepage(), 19 )); 20 } 21 22 class homepage extends statefulwidget { 23 @override 24 homepagestate createstate() => homepagestate(); 25 } 26 27 class homepagestate extends state\<homepage> { 28 list\<parseobject> results = \<parseobject>\[]; 29 double selecteddistance = 3000; 30 31 void doquerypointer() async { 32 // get publishera object 33 final querybuilder\<parseobject> publisherquerya = 34 querybuilder\<parseobject>(parseobject('publisher')) 35 whereequalto('name', 'acacia publishings'); 36 37 final parseresponse publisherresponse = await publisherquerya query(); 38 if (!publisherresponse success) { 39 return; 40 } 41 final publishera = publisherresponse results? first as parseobject; 42 43 // query books with publishera 44 final querybuilder\<parseobject> bookquery = 45 querybuilder\<parseobject>(parseobject('book')) 46 whereequalto('publisher', publishera); 47 48 final parseresponse bookresponse = await bookquery query(); 49 50 if (!bookresponse success) { 51 setstate(() { 52 results clear(); 53 }); 54 } else { 55 setstate(() { 56 results = bookresponse results as list\<parseobject>; 57 }); 58 } 59 } 60 61 void doquerymatches() async { 62 // create inner book query 63 final querybuilder\<parseobject> bookquery = 64 querybuilder\<parseobject>(parseobject('book')) 65 wheregreaterthan('publishingdate', datetime(2010, 01, 01)); 66 67 // query bookstore using inner book query 68 final querybuilder\<parseobject> bookstorequery = 69 querybuilder\<parseobject>(parseobject('bookstore')) 70 wherematchesquery('books', bookquery); 71 72 final parseresponse bookstoreresponse = await bookstorequery query(); 73 if (!bookstoreresponse success) { 74 setstate(() { 75 results clear(); 76 }); 77 } else { 78 setstate(() { 79 results = bookstoreresponse results as list\<parseobject>; 80 }); 81 } 82 } 83 84 void doqueryrelatedto() async { 85 // get book object 86 final querybuilder\<parseobject> bookquery = 87 querybuilder\<parseobject>(parseobject('book')) 88 whereequalto('title', 'can you believe it?'); 89 90 final parseresponse bookresponse = await bookquery query(); 91 if (!bookresponse success) { 92 return; 93 } 94 95 final book = bookresponse results? first as parseobject; 96 97 // get author with relation with book can you believe it? 98 final querybuilder\<parseobject> authorsquery = 99 querybuilder\<parseobject>(parseobject('author')) 100 whererelatedto('authors', 'book', book objectid!); 101 102 final parseresponse authorresponse = await authorsquery query(); 103 104 if (!authorresponse success) { 105 setstate(() { 106 results clear(); 107 }); 108 } else { 109 setstate(() { 110 results = authorresponse results as list\<parseobject>; 111 }); 112 } 113 } 114 115 void doclearresults() async { 116 setstate(() { 117 results clear(); 118 }); 119 } 120 121 @override 122 widget build(buildcontext context) { 123 return scaffold( 124 body padding( 125 padding const edgeinsets all(16 0), 126 child column( 127 crossaxisalignment crossaxisalignment stretch, 128 children \[ 129 container( 130 height 200, 131 child image network( 132 'https //blog back4app com/wp content/uploads/2017/11/logo b4a 1 768x175 1 png'), 133 ), 134 center( 135 child const text('flutter on back4app geopoint', 136 style textstyle(fontsize 18, fontweight fontweight bold)), 137 ), 138 sizedbox( 139 height 8, 140 ), 141 container( 142 height 50, 143 child elevatedbutton( 144 onpressed doquerypointer, 145 child text('query a'), 146 style elevatedbutton stylefrom(primary colors blue)), 147 ), 148 sizedbox( 149 height 8, 150 ), 151 container( 152 height 50, 153 child elevatedbutton( 154 onpressed doquerymatches, 155 child text('query b'), 156 style elevatedbutton stylefrom(primary colors blue)), 157 ), 158 sizedbox( 159 height 8, 160 ), 161 container( 162 height 50, 163 child elevatedbutton( 164 onpressed doqueryrelatedto, 165 child text('query c'), 166 style elevatedbutton stylefrom(primary colors blue)), 167 ), 168 sizedbox( 169 height 8, 170 ), 171 container( 172 height 50, 173 child elevatedbutton( 174 onpressed doclearresults, 175 child text('clear results'), 176 style elevatedbutton stylefrom(primary colors blue)), 177 ), 178 sizedbox( 179 height 8, 180 ), 181 text( 182 'result list ${results length}', 183 ), 184 expanded( 185 child listview\ builder( 186 itemcount results length, 187 itembuilder (context, index) { 188 final o = results\[index]; 189 return container( 190 padding const edgeinsets all(4), 191 decoration 192 boxdecoration(border border all(color colors black)), 193 child text('${o tostring()}'), 194 ); 195 }), 196 ) 197 ], 198 ), 199 )); 200 } 201 } 애플리케이션 id와 클라이언트 키 자격 증명을 찾으려면 back4app 웹사이트 https //www back4app com/ 로 이동하세요 back4app에서 프로젝트의 applicationid와 clientkey 값을 사용하여 main dart의 코드를 업데이트하세요 keyapplicationid = 앱 id keyclientkey = 클라이언트 키 프로젝트를 실행하면 앱이 이미지와 같이 로드됩니다 결론 이 가이드를 마치면서, parse에서 관계형 쿼리가 어떻게 작동하는지와 flutter 앱에서 back4app에서 이를 수행하는 방법을 배웠습니다 다음 가이드에서는 parse에서 사용자와 작업하는 방법을 배울 것입니다