React Native
...
Data objects
1:N Relationship
11 min
relazione uno a molti 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 sulla relazione più comune, quella uno a molti i backend di memorizzazione dei dati di solito richiederanno dichiarazioni esplicite di queste associazioni e potrebbero persino richiedere che tu crei, da solo, tabelle relazionali per gestire le loro unioni parse lo fa automaticamente per te, rimuovendo qualsiasi possibilità di errori durante la costruzione delle tue relazioni dati e accelerando il processo di modellazione della tua applicazione ci sono due modi per creare una relazione uno a molti in parse il primo è utilizzare i parse object parse object pointers, che è il più veloce in termini di creazione e tempo di query il secondo è utilizzare array array che possono portare a tempi di query lenti a seconda delle loro dimensioni a causa di questo problema di prestazioni, utilizzeremo solo esempi di puntatori d'ora in poi in questa guida, implementerai un'applicazione di registrazione di libri in react native che contiene i tre principali tipi di associazioni di dati imparerai come creare e interrogare relazioni di dati uno a molti utilizzando il tuo 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 dello schermo fornito da questa guida, dovresti configurare il react native paper react native paper https //github com/callstack/react native paper obiettivo utilizza la relazione uno a molti di parse per modellare un'app book store react native 1 comprendere la classe book poiché utilizzeremo un esempio di applicazione per la registrazione di libri in questa guida, è necessario prima comprendere come sono disposte le relazioni tra gli oggetti in questo database la classe principale dell'oggetto che utilizzerai è la book book classe, che memorizza ogni voce di libro nella registrazione inoltre, queste sono le altre quattro classi di oggetti editore editore nome dell'editore del libro, relazione uno a molti con book book genere genere genere del libro, relazione uno a molti con book book nota che per questo esempio considereremo che un libro possa avere solo un genere; autore autore autore del libro, relazione molti a molti con book book , 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 book book , 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, quindi quando un utente sceglie un'opzione di editore o genere, i campi del modulo conterranno il completo parse object parse object istanza 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 };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 bookpublisherobject bookpublisherobject e bookgenreobject bookgenreobject sono impostati sul nuovo libro parse object parse object istanza vedi quanto è semplice in parse creare una relazione uno a molti puoi assegnare l'istanza dell'oggetto target o un puntatore ad essa utilizzando il parse object set parse object set metodo, che prende due argomenti il nome del campo e il valore da impostare parse creerà una colonna di tipo dati puntatore e un collegamento diretto sulla tua dashboard per un accesso rapido sotto il cofano cliccando sul valore del puntatore dell'oggetto nel tuo cruscotto verrai portato all'entry dell'oggetto referenziato potrebbe sembrare una funzionalità innocua, ma questo rende il debug e la tracciabilità degli errori molto più rapidi rispetto alla ricerca manuale 3 interrogare relazioni uno a molti interrogare oggetti correlati uno a molti è 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 };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 relativi a un editore o genere specifico, è sufficiente 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 molti 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(('publisher') get('name') bookparseobject get(('publisher') get('name') ecco come appare lo schermo dell'elenco utilizzando questi getter per recuperare i nomi dell'editore e del genere dagli elementi dell'elenco conclusione alla fine di questa guida, hai imparato come creare e interrogare relazioni uno a molti in parse su react native nella prossima guida, ti mostreremo come eseguire interrogazioni e relazioni molti a molti e uno a uno