React Native
...
Data objects
N:N Relationship
10 min
relazione molti 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 ulteriore potere 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 tra di essi; molti a molti molti a molti , che possono creare molte relazioni complesse tra molti oggetti in questa guida, ci concentreremo sulle relazioni molti a molti queste relazioni sono comuni nelle applicazioni contenenti contenuti autoriali, come blog e feed di notizie, perché autori e tag di categoria possono essere intercambiabili e ottimizzati per query rapide i backend di memorizzazione dei dati di solito richiedono dichiarazioni esplicite di queste associazioni e persino richiedono 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 di dati e accelerando il processo di modellazione della tua applicazione ci sono due modi per creare una relazione molti a molti in parse il primo utilizza le parse object parse object relazioni, che è il più veloce in termini di creazione e tempo di query il secondo utilizza gli 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 relazioni 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 molti 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 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 di database molti a molti 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 tra gli 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 e 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 seleziona 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 }; 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 gli bookauthorsobjects bookauthorsobjects sono impostati sul nuovo libro parse object parse object istanza per creare una relazione molti a molti, devi prima creare un nuovo parse object relation parse object relation e poi aggiungere gli oggetti correlati a 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 link per un facile accesso a questa nuova tabella nella colonna del campo nel dashboard tieni presente che puoi anche gestire oggetti e aggiungerne di nuovi alla tua relazione tramite la dashboard una volta creata, quindi ricorda questa scorciatoia quando sviluppi la tua applicazione 3 interrogare relazioni molti a molti recuperare risultati da query di oggetti correlati molti a molti richiede alcuni passaggi aggiuntivi rispetto a quelli normali 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 relativi a un autore specifico, è necessario eseguire un parse query equalto parse query equalto metodo passando l' parse object parse object istanza come parametro dopo l'interrogazione, 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 dopo di che, puoi iterare sull'array di oggetti e utilizzare il parse object get parse object get metodo per recuperare il nome dell'autore ecco come appare lo schermo dell'elenco utilizzando queste procedure conclusione alla fine di questa guida, hai imparato come creare e interrogare relazioni molti a molti in parse su react native nella prossima guida, ti mostreremo come eseguire interrogazioni e relazioni uno a uno