React Native
...
Data objects
1:1 Relationship
11 min
relazione uno a uno introduzione al centro di molti backend, troverai la possibilità di memorizzare dati utilizzando parse, puoi memorizzare oggetti dati stabilendo relazioni tra di essi le relazioni dei dati standardizzano come ogni oggetto dati è correlato o associato ad altri questo può darti un potere extra quando costruisci ed esegui query complesse ci sono tre principali tipi di relazione uno a molti uno a molti , dove un oggetto può essere correlato a molti altri oggetti; uno a uno uno a uno , stabilendo relazioni dirette tra due oggetti e solo essi; molti a molti molti a molti , che possono creare molte relazioni complesse tra molti oggetti in questa guida, ci concentreremo sulle relazioni uno a uno queste relazioni sono comuni nelle applicazioni che coinvolgono dati sensibili e gestione degli utenti, che richiedono campi unici che devono essere rispettati, come numeri di identificazione e numeri di telefono i backend di archiviazione dei dati di solito richiederanno dichiarazioni esplicite di queste associazioni e parse non ha una soluzione automatica per ottenere tali associazioni tuttavia, ci sono modi per implementare relazioni 1 1 in parse utilizzando parse cloud parse cloud funzioni sul tuo server, garantendo che le relazioni tra le tabelle rimangano uniche prima di salvare i dati questo viene fatto creando beforesave beforesave funzioni in entrambe le classi correlate e impedendo il salvataggio se la classe padre possiede già un'istanza nella classe figlia, e viceversa puoi anche trattare questi casi nel codice della tua applicazione parse, interrogando il server prima di salvare e garantendo tale relazione questo sarà il modo mostrato in questa guida, ma nota che utilizzare funzioni cloud è molto più pulito e consigliato in questa guida, implementerai un'applicazione di registrazione di libri react native che contiene i tre principali tipi di associazioni di dati imparerai come creare e interrogare relazioni di dati uno a uno utilizzando back4app e react native in qualsiasi momento, puoi accedere a questo progetto tramite i nostri repository github per controllare gli stili e il codice completo https //github com/templates back4app/react native js associations https //github com/templates back4app/react native ts associations requisiti per completare questo tutorial, avrai bisogno di un'app react native creata e connessa a https //www back4app com/docs/react native/parse sdk/react native sdk se desideri testare/utilizzare il layout della schermata fornito da questa guida, dovresti configurare il react native paper react native paper https //github com/callstack/react native paper obiettivo per eseguire e dimostrare relazioni uno a uno nel database in react native utilizzando parse in uno scenario realistico 1 comprendere la classe book poiché in questa guida utilizzeremo un esempio di applicazione per la registrazione di libri, è necessario prima comprendere come sono disposte le relazioni degli oggetti in questo database la classe principale dell'oggetto che utilizzerai è la libro libro classe, che memorizzerà ogni voce di libro nella registrazione queste sono le altre quattro classi di oggetti editore editore nome dell'editore del libro, relazione uno a molti con libro libro genere genere genere del libro, relazione uno a molti con libro libro nota che per questo esempio considereremo che un libro può avere solo un genere; autore autore autore del libro, relazione molti a molti con libro libro , poiché un libro può avere più di un autore e un autore può avere più di un libro; isdb isdb numero identificativo isdb del libro, relazione uno a uno con libro libro , poiché questo numero è unico per ogni libro ecco una rappresentazione visiva di queste tabelle del database per semplicità, assumeremo che ogni classe di oggetti abbia solo un tipo di stringa nome nome attributo ( titolo titolo per il libro libro ), a parte eventuali attributi relazionali aggiuntivi 2 creare relazioni uno a molti prima di passare a questo passaggio, ti consigliamo di clonare ed eseguire l'app di esempio della libreria react native ( https //github com/templates back4app/react native js associations , https //github com/templates back4app/react native ts associations ) questa applicazione ha due schermate principali una responsabile per elencare i libri registrati e l'altra per creare nuovi libri nel modulo di registrazione del libro, ci sono collegamenti diretti agli altri oggetti correlati e un textinput textinput campo assegnato al valore isbd del libro, che sarà utilizzato per creare la tua relazione uno a uno diamo un'occhiata al metodo di creazione del libro che viene chiamato quando si invia questo modulo javascript 1 const createbook = async function () { 2 try { 3 // these values come from state variables linked to 4 // the screen form fields, retrieving the user choices 5 // as a complete parse object, when applicable; 6 const booktitlevalue = booktitle; 7 const bookisbdvalue = bookisbd; 8 // for example, bookpublisher holds the value from 9 // radiobutton group field with its options being every 10 // publisher parse object instance saved on server, which is 11 // queried on screen load via useeffect 12 const bookpublisherobject = bookpublisher; 13 const bookgenreobject = bookgenre; 14 // bookauthors can be an array of parse objects, since the book 15 // may have more than one author 16 const bookauthorsobjects = bookauthors; 17	 18 // creates a new parse object instance 19 let book = new parse object('book'); 20	 21 // set data to parse object 22 // simple title field 23 book set('title', booktitlevalue); 24	 25 // 1 1 relation, need to check for uniqueness of value before creating a new isbd object 26 let isbdquery = new parse query('isbd'); 27 isbdquery equalto('name', bookisbdvalue); 28 let isbdqueryresult = await isbdquery first(); 29 if (isbdqueryresult !== null && isbdqueryresult !== undefined) { 30 // if first returns a valid object instance, it means that there 31 // is at least one instance of isbd with the informed value 32 alert alert( 33 'error!', 34 'there is already an isbd instance with this value!', 35 ); 36 return false; 37 } else { 38 // create a new isbd object instance to create a one to one relation on saving 39 let isbd = new parse object('isbd'); 40 isbd set('name', bookisbdvalue); 41 isbd = await isbd save(); 42 // set the new object to the new book object isbd field 43 book set('isbd', isbd); 44 } 45	 46 // one to many relations can be set in two ways 47 // add direct object to field (parse will convert to pointer on save) 48 book set('publisher', bookpublisherobject); 49 // or add pointer to field 50 book set('genre', bookgenreobject topointer()); 51	 52 // many to many relation 53 // create a new relation so data can be added 54 let authorsrelation = book relation('authors'); 55 // bookauthorsobjects is an array of parse objects, 56 // you can add to relation by adding the whole array or object by object 57 authorsrelation add(bookauthorsobjects); 58	 59 // after setting the values, save it on the server 60 try { 61 await book save(); 62 // success 63 alert alert('success!'); 64 navigation goback(); 65 return true; 66 } catch (error) { 67 // error can be caused by lack of internet connection 68 alert alert('error!', error message); 69 return false; 70 } 71 } catch (error) { 72 // error can be caused by lack of value selection 73 alert alert( 74 'error!', 75 'make sure to select valid choices in publisher, genre and author fields!', 76 ); 77 return false; 78 } 79 }; todolist tsx 1 const createbook = async function () promise\<boolean> { 2 try { 3 // these values come from state variables linked to 4 // the screen form fields, retrieving the user choices 5 // as a complete parse object, when applicable; 6 const booktitlevalue string = booktitle; 7 const bookisbdvalue string = bookisbd; 8 // for example, bookpublisher holds the value from 9 // radiobutton group field with its options being every 10 // publisher parse object instance saved on server, which is 11 // queried on screen load via useeffect 12 const bookpublisherobject parse object = bookpublisher; 13 const bookgenreobject parse object = bookgenre; 14 // bookauthors can be an array of parse objects, since the book 15 // may have more than one author 16 const bookauthorsobjects \[parse object] = bookauthors; 17	 18 // creates a new parse object instance 19 let book parse object = new parse object('book'); 20	 21 // set data to parse object 22 // simple title field 23 book set('title', booktitlevalue); 24	 25 // 1 1 relation, need to check for uniqueness of value before creating a new isbd object 26 let isbdquery parse query = new parse query('isbd'); 27 isbdquery equalto('name', bookisbdvalue); 28 let isbdqueryresult parse object = await isbdquery first(); 29 if (isbdqueryresult !== null && isbdqueryresult !== undefined) { 30 // if first returns a valid object instance, it means that there 31 // is at least one instance of isbd with the informed value 32 alert alert( 33 'error!', 34 'there is already an isbd instance with this value!', 35 ); 36 return false; 37 } else { 38 // create a new isbd object instance to create a one to one relation on saving 39 let isbd parse object = new parse object('isbd'); 40 isbd set('name', bookisbdvalue); 41 isbd = await isbd save(); 42 // set the new object to the new book object isbd field 43 book set('isbd', isbd); 44 } 45	 46 // one to many relations can be set in two ways 47 // add direct object to field (parse will convert to pointer on save) 48 book set('publisher', bookpublisherobject); 49 // or add pointer to field 50 book set('genre', bookgenreobject topointer()); 51	 52 // many to many relation 53 // create a new relation so data can be added 54 let authorsrelation = book relation('authors'); 55 // bookauthorsobjects is an array of parse objects, 56 // you can add to relation by adding the whole array or object by object 57 authorsrelation add(bookauthorsobjects); 58	 59 // after setting the values, save it on the server 60 try { 61 await book save(); 62 // success 63 alert alert('success!'); 64 navigation goback(); 65 return true; 66 } catch (error) { 67 // error can be caused by lack of internet connection 68 alert alert('error!', error message); 69 return false; 70 } 71 } catch (error) { 72 // error can be caused by lack of value selection 73 alert alert( 74 'error!', 75 'make sure to select valid choices in publisher, genre and author fields!', 76 ); 77 return false; 78 } 79 }; guarda come il bookisbdvalue bookisbdvalue è impostato sul nuovo libro parse object parse object istanza creare e salvare relazioni uno a uno e uno a molti in parse sono processi simili, in cui passi come argomento l' parse object parse object istanza usando il parse object set parse object set metodo, che prende due argomenti il nome del campo e il valore da impostare il problema qui è che, prima di salvare, devi assicurarti che non ci siano isbd isbd oggetti contenenti il valore della stringa id isbd informato nel tuo database e che non ci siano libro libro oggetti già correlati ad esso la seconda parte sarà sempre vera in questo caso, poiché stai creando un nuovo libro libro oggetto ogni volta l'applicazione dell'unicità di isbd isbd può essere ottenuta utilizzando la seguente query evidenziata javascript 1 let isbdquery = new parse query('isbd'); 2 isbdquery equalto('name', bookisbdvalue); 3 let isbdqueryresult = await isbdquery first(); 4 if (isbdqueryresult !== null && isbdqueryresult !== undefined) { 5 // if first returns a valid object instance, it means that there 6 // is at least one instance of isbd with the informed value 7 alert alert( 8 'error!', 9 'there is already an isbd instance with this value!', 10 ); 11 return false; 12 } todolist tsx 1 let isbdquery parse query = new parse query('isbd'); 2 isbdquery equalto('name', bookisbdvalue); 3 let isbdqueryresult parse object = await isbdquery first(); 4 if (isbdqueryresult !== null && isbdqueryresult !== undefined) { 5 // if first returns a valid object instance, it means that there 6 // is at least one instance of isbd with the informed value 7 alert alert( 8 'error!', 9 'there is already an isbd instance with this value!', 10 ); 11 return false; 12 } dopo aver salvato con successo i tuoi oggetti, parse creerà una colonna di tipo dati puntatore e un collegamento diretto sulla tua dashboard per un accesso rapido in background 3 interrogare relazioni uno a uno interrogare oggetti correlati uno a uno è piuttosto semplice poiché gran parte di esso è gestito da parse dai un'occhiata alla funzione di query nella schermata dell'elenco dei registri del libro javascript 1 const querybooks = async function () { 2 // these values come from state variables linked to 3 // the screen query radiobutton group fields, with its options being every 4 // parse object instance saved on server from the referred class, which is 5 // queried on screen load via useeffect; these variables retrievie the user choices 6 // as a complete parse object; 7 const querypublishervalue = querypublisher; 8 const querygenrevalue = querygenre; 9 const queryauthorvalue = queryauthor; 10 const queryisbdvalue = queryisbd; 11	 12 // reading parse objects is done by using parse query 13 const parsequery = new parse query('book'); 14	 15 // one to many queries 16 if (querypublishervalue !== '') { 17 parsequery equalto('publisher', querypublishervalue); 18 } 19 if (querygenrevalue !== '') { 20 parsequery equalto('genre', querygenrevalue); 21 } 22	 23 // one to one query 24 if (queryisbdvalue !== '') { 25 parsequery equalto('isbd', queryisbdvalue); 26 } 27	 28 // many to many query 29 // in this case, we need to retrieve books related to the chosen author 30 if (queryauthorvalue !== '') { 31 parsequery equalto('authors', queryauthorvalue); 32 } 33	 34 try { 35 let books = await parsequery find(); 36 // many to many objects retrieval 37 // in this example we need to get every related author parse object 38 // and add it to our query result objects 39 for (let book of books) { 40 // this query is done by creating a relation and querying it 41 let bookauthorsrelation = book relation('authors'); 42 book authorsobjects = await bookauthorsrelation query() find(); 43 } 44 setqueriedbooks(books); 45 return true; 46 } catch (error) { 47 // error can be caused by lack of internet connection 48 alert alert('error!', error message); 49 return false; 50 } 51 }; todolist tsx 1 const querybooks = async function () promise\<boolean> { 2 // these values come from state variables linked to 3 // the screen query radiobutton group fields, with its options being every 4 // parse object instance saved on server from the referred class, which is 5 // queried on screen load via useeffect; these variables retrievie the user choices 6 // as a complete parse object; 7 const querypublishervalue parse object = querypublisher; 8 const querygenrevalue parse object = querygenre; 9 const queryauthorvalue parse object = queryauthor; 10 const queryisbdvalue parse object = queryisbd; 11	 12 // reading parse objects is done by using parse query 13 const parsequery parse query = new parse query('book'); 14	 15 // one to many queries 16 if (querypublishervalue !== '') { 17 parsequery equalto('publisher', querypublishervalue); 18 } 19 if (querygenrevalue !== '') { 20 parsequery equalto('genre', querygenrevalue); 21 } 22	 23 // one to one query 24 if (queryisbdvalue !== '') { 25 parsequery equalto('isbd', queryisbdvalue); 26 } 27	 28 // many to many query 29 // in this case, we need to retrieve books related to the chosen author 30 if (queryauthorvalue !== '') { 31 parsequery equalto('authors', queryauthorvalue); 32 } 33	 34 try { 35 let books \[parse object] = await parsequery find(); 36 // many to many objects retrieval 37 // in this example we need to get every related author parse object 38 // and add it to our query result objects 39 for (let book of books) { 40 // this query is done by creating a relation and querying it 41 let bookauthorsrelation = book relation('authors'); 42 book authorsobjects = await bookauthorsrelation query() find(); 43 } 44 setqueriedbooks(books); 45 return true; 46 } catch (error) { 47 // error can be caused by lack of internet connection 48 alert alert('error!', error message); 49 return false; 50 } 51 }; in questo caso, per interrogare eventuali libri correlati a un isbd specifico, è necessario eseguire un parse query equalto parse query equalto metodo passando l' parse object parse object istanza come parametro dopo l'interrogazione, parse memorizzerà all'interno degli oggetti risultanti le istanze complete di eventuali campi relazionali uno a uno per recuperare e mostrare i dati da queste istanze di oggetti, puoi concatenare il parse object get parse object get metodo in questo modo bookparseobject get(('isbd') get('name') bookparseobject get(('isbd') get('name') ecco come appare lo schermo dell'elenco utilizzando questi getter per recuperare il nome isbd dagli elementi dell'elenco conclusione alla fine di questa guida, hai imparato come creare e interrogare relazioni uno a uno in parse su react native nella prossima guida, ti mostreremo come registrare gli utenti