ReactJS
Data objects
Gestione relazioni dati in React con Parse: guida avanzata
15 min
relazioni introduzione utilizzando parse, puoi memorizzare oggetti di dati stabilendo relazioni tra di essi per modellare questo comportamento, qualsiasi parseobject parseobject può essere utilizzato come valore in altri parseobject parseobject internamente, il framework parse memorizzerà l'oggetto a cui si fa riferimento in un solo posto, per mantenere la coerenza 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; molti a molti molti a molti , che può creare molte relazioni complesse tra molti oggetti uno a uno uno a uno , stabilendo relazioni dirette tra due oggetti e solo tra di essi; ci sono due modi per creare una relazione uno a molti relazione uno a molti in parse (consigliato) il primo è utilizzare i parse pointers parse pointers nella classe figlia, che è il più veloce in termini di creazione e tempo di query utilizzeremo questo in questa guida il secondo è utilizzare array array di parse pointers parse pointers nella classe genitore, il che può portare a tempi di query lenti a seconda delle loro dimensioni a causa di questo problema di prestazioni, utilizzeremo solo esempi di puntatori ci sono tre modi per creare una relazione molti a molti relazione molti a molti in parse (consigliato) il primo è utilizzare parse relations parse relations , che è il più veloce in termini di creazione e tempo di query useremo questo in questa guida il secondo è utilizzare array array di parse pointers parse pointers che possono portare a tempi di query lenti a seconda delle loro dimensioni il terzo è utilizzare jointable jointable dove l'idea proviene da database classici quando c'è una relazione molti a molti, combiniamo ogni objectid objectid o pointer pointer da entrambi i lati insieme per costruire una nuova tabella separata in cui viene tracciata la relazione in questa guida, implementerai un'applicazione di registrazione di libri in react che contiene i tre principali tipi di associazioni di dati imparerai come creare e interrogare relazioni di dati utilizzando back4app e react in qualsiasi momento, puoi accedere a questo progetto tramite i nostri repository github per controllare gli stili e il codice completo repository di esempio javascript repository di esempio typescript requisiti per completare questo tutorial, avrai bisogno di un'app react creata e connessa a back4app se desideri eseguire il progetto di esempio di questa guida, dovresti configurare la ant design ant design libreria obiettivo per eseguire e dimostrare le relazioni del database in react 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 book book 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 book book ; genere genere genere del libro, relazione uno a molti con book book nota che per questo esempio considereremo che un libro può 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 passo 2 creazione delle relazioni prima di passare a questo passo, ti consigliamo di clonare e eseguire l'esempio dell'app react ( repository esempio javascript , repository esempio typescript ) 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 campo di input di testo assegnato al valore isbd del libro, che sarà utilizzato per creare la 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 // radiogroup 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 // one to one (1 1) 26 // 1 1 relation, need to check for uniqueness of value before creating a new isbd object 27 let isbdquery = new parse query('isbd'); 28 isbdquery equalto('name', bookisbdvalue); 29 let isbdqueryresult = await isbdquery first(); 30 if (isbdqueryresult !== null && isbdqueryresult !== undefined) { 31 // if first returns a valid object instance, it means that there 32 // is at least one instance of isbd with the informed value 33 alert( 34 'error! 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 (1\ n) 47 // one to many relations can be set in two ways 48 // add direct object to field (parse will convert to pointer on save) 49 book set('publisher', bookpublisherobject); 50 // or add pointer to field 51 book set('genre', bookgenreobject topointer()); 52 53 // many to many (n\ n) 54 // create a new relation so data can be added 55 let authorsrelation = book relation('authors'); 56 // bookauthorsobjects is an array of parse objects, 57 // you can add to relation by adding the whole array or object by object 58 authorsrelation add(bookauthorsobjects); 59 60 // after setting the values, save it on the server 61 try { 62 await book save(); 63 // success 64 alert('success!'); 65 // navigate back to home screen using react router 66 history push('/'); 67 return true; 68 } catch (error) { 69 // error can be caused by lack of internet connection 70 alert(`error! ${error message}`); 71 return false; 72 } 73 } catch (error) { 74 // error can be caused by lack of value selection 75 alert( 76 'error! make sure to select valid choices in publisher, genre and author fields!', 77 ); 78 return false; 79 } 80 }; typescript 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 // one to one (1 1) 26 // 1 1 relation, need to check for uniqueness of value before creating a new isbd object 27 let isbdquery parse query = new parse query('isbd'); 28 isbdquery equalto('name', bookisbdvalue); 29 let isbdqueryresult parse object = await isbdquery first(); 30 if (isbdqueryresult !== null && isbdqueryresult !== undefined) { 31 // if first returns a valid object instance, it means that there 32 // is at least one instance of isbd with the informed value 33 alert( 34 'error! 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 (1\ n) 47 // one to many relations can be set in two ways 48 // add direct object to field (parse will convert to pointer on save) 49 book set('publisher', bookpublisherobject); 50 // or add pointer to field 51 book set('genre', bookgenreobject topointer()); 52 53 // many to many (n\ n) 54 // create a new relation so data can be added 55 let authorsrelation = book relation('authors'); 56 // bookauthorsobjects is an array of parse objects, 57 // you can add to relation by adding the whole array or object by object 58 authorsrelation add(bookauthorsobjects); 59 60 // after setting the values, save it on the server 61 try { 62 await book save(); 63 // success 64 alert('success!'); 65 // navigate back to home screen using react router 66 history push('/'); 67 return true; 68 } catch (error) { 69 // error can be caused by lack of internet connection 70 alert(`error! ${error message}`); 71 return false; 72 } 73 } catch (error) { 74 // error can be caused by lack of value selection 75 alert( 76 'error! make sure to select valid choices in publisher, genre and author fields!', 77 ); 78 return false; 79 } 80 }; esaminiamo ora separatamente come vengono effettuati i tre tipi di associazioni quando si crea l' libro libro oggetto relazione uno a molti nota 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 sul tuo dashboard per un accesso rapido sotto il cofano relazione molti a molti guarda come i bookauthorsobjects bookauthorsobjects sono impostati sulla nuova istanza di libro parse object parse object per creare una relazione molti a molti, devi prima creare un nuovo parse object relation parse object relation e poi aggiungere gli oggetti correlati ad esso uno per uno o passando un array di parse object parse object utilizzando il parse object relation add parse object relation add metodo parse creerà una colonna di tipo relazione e anche una tabella relazionale nel tuo database parse creerà anche un collegamento per un facile accesso a questa nuova tabella nella colonna del campo nel dashboard relazione uno a uno guarda come il bookisbdvalue bookisbdvalue è impostato sul nuovo libro parse objec parse objec t instance 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 utilizzando il parse object set parse object set metodo, che accetta 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 book book oggetti già correlati ad esso la seconda parte sarà sempre vera in questo caso, poiché stai creando un nuovo book book oggetto ogni volta assicurare l' isbd isbd unicità può essere ottenuto 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( 8 'error! there is already an isbd instance with this value!', 9 ); 10 return false; 11 } typescript 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( 8 'error! there is already an isbd instance with this value!', 9 ); 10 return false; 11 } dopo aver salvato con successo i tuoi oggetti, parse creerà anche una colonna di tipo dati puntatore e un collegamento diretto sul tuo dashboard 3 interrogare relazioni interrogare oggetti correlati è piuttosto semplice poiché gran parte di esso è gestita da parse dai un'occhiata alla funzione di query nella schermata dell'elenco dei registri del libro e dopo evidenzieremo come ciascun tipo di relazione viene interrogato 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(`error! ${error message}`); 49 return false; 50 } 51 }; typescript 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(`error! ${error message}`); 49 return false; 50 } 51 }; query uno a molti per interrogare qualsiasi libro relativo a un editore o genere specifico, è necessario eseguire un parse query equalt parse query equalt metodo passando il parse object parse object istanza come parametro dopo l'interrogazione, parse memorizzerà all'interno degli oggetti risultanti le istanze complete di qualsiasi campo relazionale 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') query molti a molti per interrogare qualsiasi libro relativo a un autore specifico, la query utilizzerà anche solo un parse query equalto parse query equalto metodo tuttavia, dopo aver interrogato, parse non memorizzerà parse object parse object istanze da campi relazionali molti a molti, solo un riferimento al nome della classe correlata, come {" type" "relation", "classname" "author"} {" type" "relation", "classname" "author"} per recuperare e mostrare i dati da queste istanze di oggetti, è necessario creare una relazione e interrogarla di nuovo, memorizzando i risultati in un array di oggetti di propria creazione query uno a uno proprio come prima, per interrogare qualsiasi libro relativo a un isbd specifico, è necessario eseguire un parse query equalto parse query equalto metodo passando l' parse object parse object istanza come parametro dopo aver interrogato, parse memorizzerà all'interno degli oggetti risultanti le istanze complete di qualsiasi campo relazionale uno a uno, nello stesso modo in cui viene fatto con i campi relazionali uno a molti conclusione alla fine di questa guida, hai imparato come creare e interrogare relazioni in parse su react nella prossima guida, ti mostreremo come registrare gli utenti