Get started
관계 스키마
14 분
이 가이드는 back4app에서 관계형 스키마를 사용하는 방법을 설명합니다 관련 클래스를 생성하고 parse server를 사용하여 효율적인 쿼리를 수행하는 방법을 포함합니다 포인터 와 관계 를 효과적으로 사용하는 방법과 실용적인 예제를 배울 수 있습니다 관계형 스키마란 무엇인가요? 관계형 스키마는 데이터를 서로 연결된 다양한 클래스로 구성합니다 parse server에서는 이러한 관계가 다음을 통해 관리됩니다 포인터 단일 객체를 직접 참조합니다 관계 여러 연결(다대다 관계)을 관리합니다 이 도구들은 복잡한 쿼리를 효율적이고 일관되게 수행할 수 있게 해줍니다 목표 이 가이드를 마치면 다음을 할 수 있게 됩니다 포인터 와 관계 를 사용하여 클래스 간의 관계를 생성합니다 연결된 데이터를 검색하기 위한 관계형 쿼리를 수행합니다 더 나은 성능을 위해 스키마를 최적화합니다 전제 조건 back4app 애플리케이션 앱 만들기 가이드 https //www back4app com/docs/get started/new parse app parse sdk 설치됨 설치 가이드 https //www back4app com/docs/get started/parse sdk 1 관련 클래스 만들기 실용적인 예 주와 도시 도시가 주와 연관된 시스템을 모델링하고 싶다고 상상해 보세요 state name 필드를 가진 state 클래스 city name 필드를 가진 city 클래스와 state 에 대한 포인터 클래스 및 관계 생성 javascript async function createstateandcity() { try { // create a state const state = parse object extend('state'); const california = new state(); california set('state name', 'california'); const savedstate = await california save(); console log(`state created with objectid ${savedstate id}`); // create a city with a pointer to state const city = parse object extend('city'); const losangeles = new city(); losangeles set('city name', 'los angeles'); losangeles set('state', savedstate); const savedcity = await losangeles save(); console log(`city created with objectid ${savedcity id}`); } catch (error) { console error('error creating state and city ', error message); } } createstateandcity(); flutter future\<void> createclasses() async { await parse() initialize('your app id', 'https //parseapi back4app com/', clientkey 'your client key', autosendsessionid true); // create a state final state = parseobject('state') set('state name', 'california'); final stateresult = await state save(); if (stateresult success) { // create a city with a pointer to state final city = parseobject('city') set('city name', 'los angeles') set('state', state); final cityresult = await city save(); if (cityresult success) { print('state and city created successfully '); } } } android public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super oncreate(savedinstancestate); setcontentview(r layout activity main); // initialize parse parse initialize(new parse configuration builder(this) applicationid("your app id") clientkey("your client key") server("https //parseapi back4app com/") build() ); // create state and city createclasses(); } private void createclasses() { // create a state parseobject state = new parseobject("state"); state put("state name", "california"); state saveinbackground(e > { if (e == null) { log d("parse", "state created successfully with objectid " + state getobjectid()); // save city with a pointer to state parseobject city = new parseobject("city"); city put("city name", "los angeles"); city put("state", state); city saveinbackground(ex > { if (ex == null) { log d("parse", "city created successfully with objectid " + city getobjectid()); } else { log e("parse", "failed to create city " + ex getmessage()); } }); } else { log e("parse", "failed to create state " + e getmessage()); } }); } } ios struct state parseobject { var objectid string? var state name string? var createdat date? var updatedat date? } struct city parseobject { var objectid string? var city name string? var state state? var createdat date? var updatedat date? } func createclasses() async throws { try await parseswift initialize(applicationid "your app id", clientkey "your client key", serverurl url(string "https //parseapi back4app com")!) let state = state(state name "california") let savedstate = try await state save() var city = city(city name "los angeles", state savedstate) city = try await city save() print("state and city created successfully ") } php require 'vendor/autoload php'; use parse\parseclient; use parse\parseobject; parseclient initialize('your app id', 'your client key', 'https //parseapi back4app com/'); try { // create a state $state = new parseobject("state"); $state >set("state name", "california"); $state >save(); // create a city with a pointer to state $city = new parseobject("city"); $city >set("city name", "los angeles"); $city >set("state", $state); $city >save(); echo "state and city created successfully "; } catch (exception $ex) { echo "error " $ex >getmessage(); } net namespace parseexampleapp { class program { static async task main(string\[] args) { // initialize parse parseclient initialize(new parseclient configuration { applicationid = "your app id", server = "https //parseapi back4app com/", key = "your client key" }); // call the method to create state and city await createclassesasync(); } static async task createclassesasync() { try { // create a state var state = new parseobject("state"); state\["state name"] = "california"; await state saveasync(); console writeline($"state created with objectid {state objectid}"); // create a city with a pointer to the state var city = new parseobject("city"); city\["city name"] = "los angeles"; city\["state"] = state; // set the pointer to the state await city saveasync(); console writeline($"city created with objectid {city objectid}"); } catch (exception ex) { console writeline($"error {ex message}"); } } } } rest api # create state curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"state name" "california"}' \\ https //parseapi back4app com/classes/state \# use the objectid of the created state to create a city curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"city name" "los angeles", "state" {" type" "pointer", "classname" "state", "objectid" "state object id"}}' \\ https //parseapi back4app com/classes/city 2 관련 데이터 쿼리하기 이제 데이터가 관련되었으므로, 이를 검색하기 위한 쿼리를 수행할 수 있습니다 예제 1 특정 주의 도시 가져오기 javascript const statequery = new parse query("state"); statequery equalto("state name", "california"); statequery first() then(state => { const cityquery = new parse query("city"); cityquery equalto("state", state); return cityquery find(); }) then(cities => { cities foreach(city => { console log(`city ${city get("city name")}`); }); }) catch(error => { console error("error fetching cities ", error message); }); flutter final statequery = querybuilder(parseobject('state')) whereequalto('state name', 'california'); final stateresult = await statequery query(); if (stateresult success && stateresult results != null) { final state = stateresult results! first; final cityquery = querybuilder(parseobject('city')) whereequalto('state', state); final cityresult = await cityquery query(); if (cityresult success && cityresult results != null) { for (var city in cityresult results!) { print('city ${city get\<string>('city name')}'); } } } android parsequery\<parseobject> statequery = parsequery getquery("state"); statequery whereequalto("state name", "california"); statequery getfirstinbackground((state, e) > { if (e == null) { parsequery\<parseobject> cityquery = parsequery getquery("city"); cityquery whereequalto("state", state); cityquery findinbackground((cities, ex) > { if (ex == null) { for (parseobject city cities) { log d("parse", "city " + city getstring("city name")); } } else { log e("parse", "error fetching cities " + ex getmessage()); } }); } else { log e("parse", "error fetching state " + e getmessage()); } }); ios let statequery = state query("state name" == "california") statequery first { result in switch result { case success(let state) let cityquery = city query("state" == state) cityquery find { cityresult in switch cityresult { case success(let cities) cities foreach { city in print("city \\(city city name ?? "unknown")") } case failure(let error) print("error fetching cities \\(error localizeddescription)") } } case failure(let error) print("error fetching state \\(error localizeddescription)") } } php use parse\parsequery; // query state $statequery = new parsequery("state"); $statequery >equalto("state name", "california"); $state = $statequery >first(); if ($state) { // query cities $cityquery = new parsequery("city"); $cityquery >equalto("state", $state); $cities = $cityquery >find(); foreach ($cities as $city) { echo "city " $city >get("city name") "\n"; } } net var statequery = new parsequery\<parseobject>("state") whereequalto("state name", "california"); var state = await statequery firstasync(); if (state != null) { var cityquery = new parsequery\<parseobject>("city") whereequalto("state", state); var cities = await cityquery findasync(); foreach (var city in cities) { console writeline($"city {city\["city name"]}"); } } rest api # query state curl x get \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ "https //parseapi back4app com/classes/state?where={\\"state name\\" \\"california\\"}" \# query cities \# replace state object id with the objectid from the state query curl x get \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ "https //parseapi back4app com/classes/city?where={\\"state\\" {\\" type\\" \\"pointer\\",\\"classname\\" \\"state\\",\\"objectid\\" \\"state object id\\"}}" 예제 2 관련 도시와 함께 쿼리 상태 도시에 연결된 주를 반환하는 쿼리를 생성하십시오 javascript const statequery = new parse query("state"); const cityquery = new parse query("city"); cityquery matchesquery("state", statequery); cityquery include("state"); cityquery find() then(cities => { cities foreach(city => { const state = city get("state"); console log(`city ${city get("city name")} belongs to state ${state get("state name")}`); }); }) catch(error => { console error("error fetching data ", error message); }); flutter final statequery = querybuilder(parseobject('state')); final cityquery = querybuilder(parseobject('city')) wherematchesquery('state', statequery) includeobject(\['state']); final cityresult = await cityquery query(); if (cityresult success && cityresult results != null) { for (var city in cityresult results!) { final state = city get\<parseobject>('state'); print('city ${city get\<string>('city name')} belongs to state ${state? get\<string>('state name')}'); } } android parsequery\<parseobject> statequery = parsequery getquery("state"); parsequery\<parseobject> cityquery = parsequery getquery("city"); cityquery wherematchesquery("state", statequery); cityquery include("state"); cityquery findinbackground((cities, e) > { if (e == null) { for (parseobject city cities) { parseobject state = city getparseobject("state"); log d("parse", "city " + city getstring("city name") + " belongs to state " + state getstring("state name")); } } else { log e("parse", "error " + e getmessage()); } }); ios let statequery = state query() let cityquery = city query(matchesquery(key "state", query statequery)) cityquery include("state") cityquery find { result in switch result { case success(let cities) cities foreach { city in if let state = city state { print("city \\(city city name ?? "unknown") belongs to state \\(state state name ?? "unknown")") } } case failure(let error) print("error \\(error localizeddescription)") } } php use parse\parsequery; $statequery = new parsequery("state"); $cityquery = new parsequery("city"); $cityquery >matchesquery("state", $statequery); $cityquery >includekey("state"); $cities = $cityquery >find(); foreach ($cities as $city) { $state = $city >get("state"); echo "city " $city >get("city name") " belongs to state " $state >get("state name") "\n"; } net var statequery = new parsequery\<parseobject>("state"); var cityquery = new parsequery\<parseobject>("city") wherematchesquery("state", statequery) include("state"); var cities = await cityquery findasync(); foreach (var city in cities) { var state = city get\<parseobject>("state"); console writeline($"city {city\["city name"]} belongs to state {state\["state name"]}"); } rest api curl x get \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ "https //parseapi back4app com/classes/city?where={\\"state\\" {\\"$inquery\\" {\\"classname\\" \\"state\\"}}}\&include=state" 모범 사례 back4app의 parse server를 사용하여 관계형 스키마로 효과적으로 작업하려면 성능, 유지 관리 및 확장성을 보장하기 위해 다음 모범 사례를 따르십시오 올바른 관계 유형 선택 포인터 사용 for 일대일 관계 , 예를 들어 사용자를 프로필에 연결하는 경우 관계 사용 for 다대다 관계 , 예를 들어 프로젝트를 여러 작업에 연결하는 경우 효율적인 쿼리 작성 사용하기 include() 관련 데이터를 동일한 쿼리에서 로드하여 여러 요청의 필요성을 줄입니다 결과 제한하기 limit() 및 skip() 를 사용하여 한 번에 대량의 데이터 세트를 가져오는 것을 피합니다 자주 쿼리되는 필드 인덱싱하기 검색 속도를 높입니다 과도한 중첩 피하기 쿼리를 평탄하게 유지하기 복잡성을 줄이고 성능을 향상시킵니다 중첩 쿼리는 가급적 적게 사용하고 필요할 때만 사용하세요 복잡한 쿼리를 클라우드 코드로 오프로드하기 여러 관계가 포함된 복잡한 쿼리 또는 대량의 데이터 세트에 대해서는 클라우드 코드 로 오프로드하여 클라이언트를 가볍고 반응성이 있도록 유지하세요 결론 이 가이드에서는 클래스 간의 관계를 생성하고 back4app에서 관련 객체를 쿼리하는 방법을 배웠습니다 특정 sdk 문서 https //docs parseplatform org 를 계속 탐색하여 더 깊이 들어가세요!