问题
My request is very similar to Retrieving parent plus related children in one Parse REST API call, however I didn't see the final RESTful command which populated the related children.
I can obviously make multiple RESTful calls but this is redundant and introduces undesired latency. I'd rather be able to make a join request in my RESTful query.
Alternatively I could build out a job that returns the EventSeries + Children Events but that seems inappropriate and would introduce additional development and maintenance for something I'm certain is a regular request from the Parse.com community.
Parse.com cloud job to generate some mock test data is provided below. Note that I am using a factory to generate random data for my Parse.Object (don't let that trip you up).
var chance = require('cloud/lib/chance/chance.js').Chance();
var Factory = require('cloud/lib/rosie/src/rosie.js').Factory;
Parse.Cloud.define("buildRelationalEvents", function(request, response) {
var EventSeries = Parse.Object.extend("EventSeries");
var Event = Parse.Object.extend("Event");
Factory.define('Event', Event)
.attr('title', function(){ return chance.sentence({words: 3}); })
.attr('datetime', function(){ return chance.date({ year: 2015, month: chance.pick([3,4,5,6,7,8,9]) }); })
.attr('duration', function(){ return chance.pick([3600000, 1800000]); })
.attr('link', function(){ return (chance.bool({likelihood: 30}) ? undefined : chance.url() ); })
.attr('summary', function(){ return chance.paragraph(); });
Factory.define('EventSeries', EventSeries)
.attr('title', function(){ return chance.sentence({words: 3}); })
.attr('propagandaImageSrc', function(){ return 'images/something.jpg'; });
var events = Factory.buildList('Event', chance.integer({min: 5, max: 20}) );
var query = new Parse.Query(Parse.User);
query.equalTo('username','someone');
return query.first().then(function(user){
console.log(user.get('username')+" found");
var promises = [];
events.forEach(function(event){
event.set('author', user);
promises.push(event.save());
});
return Parse.Promise.when(promises);
})
.then(function(){
var series = Factory.build('EventSeries');
var relation = series.relation("events");
relation.add(events);
return series.save();
})
.then(response.success, response.error);
});
The relationship is appropriately built:
My curl command to get the children of the SeriesEvent:
curl -X GET \
-H "X-Parse-Application-Id: <APP_ID>" \
-H "X-Parse-REST-API-Key:<API_KEY>" \
-G \
--data-urlencode 'count=1' \
--data-urlencode 'include=event.eventseries' \
--data-urlencode 'where={"$relatedTo":{"object":{"__type":"Pointer","className":"EventSeries","objectId":"LbwZXewwjl"},"key":"events"}}' \
https://api.parse.com/1/classes/Event
Results of my curl command to leverage the RESTful api:
{"results":[
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.764Z","datetime":{"__type":"Date","iso":"2015-10-06T02:53:49.866Z"},"duration":3600000,"link":"http://nu.net/jidez","objectId":"6HFzsYftEz","summary":"Wimzunu ufpinu emune olo pa caledpe ze miufvo foko dujhekir zo en ewiniuh jebson. Fukovunad pe lewgecim girkaw ihozevdop tefnen sikabu guba usemarsew ki iviv paw zow logadah. Gawnenaz pimfe wazi adtekin vozo dodu vo mufas riane sekfuh sanof vugrofan. Bodozus akkuc giuciki dairujom coh kuc okacirut juke cab kikedfom panuniguh ga vav wa. Wehlo alag jovi nojru tazovuw efbufune iv kulup tuaf hajota hofob jubsiawo gevte gesmuc gocpu azobir woehi.","title":"Cozjesum pu fow.","updatedAt":"2015-05-01T05:45:05.764Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.862Z","datetime":{"__type":"Date","iso":"2015-09-03T08:35:52.008Z"},"duration":3600000,"link":"http://sug.gov/luvjos","objectId":"6swYOguX5w","summary":"Kaw furiha gari iv zitvacez kiwhoste en fuhepta wijuce laho uzter hosgelwik pe ke nurifrat. Vejubi sesnu riamasas vemijve rafhekdi irja rebfa cuppu wihiud hofora nenopfo juuf. Upiedew pinrebile hufluzsus bic fubvulu samup goh pir mup huv sa juzi geic zepwo nibko afhet zosig nibuv. Jezebo simkede tiokomic wa kipitkiz gesuz aw seha cel kihi cotos mok ipge veow.","title":"Ko wigidu kumu.","updatedAt":"2015-05-01T05:45:05.862Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.764Z","datetime":{"__type":"Date","iso":"2015-08-20T05:46:07.193Z"},"duration":1800000,"link":"http://me.com/jimkilodu","objectId":"Uc5sO2QnUx","summary":"Ub cododniz nuluja umibopani azehu zamid jas semefo abu bimokco fa haur korlaime et ik vev. Otubifdog ev du zoan uro iku diglited obead not wag awove sawuvo. Oworiknuf cug towigvu gewon torzup upejiol gahmot avgefcaf ja jazorhab vet vavcikoj tage dotuva hoopa sugfig. Zatfu huwu muruv otak iveuno zuowi gi vomicnik nofil oda lobugemo hufsu lohieb gebtu fo.","title":"Ra ojivicoz ke.","updatedAt":"2015-05-01T05:45:05.764Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.788Z","datetime":{"__type":"Date","iso":"2015-10-13T06:31:18.483Z"},"duration":1800000,"objectId":"cB7dYlRE9H","summary":"Jopewofo kusug huvmovab lojfevke lajnahnis emka jasin iro megbor erge owi imi fat vekvuci joz titjelo liduru delvu. Ref ud gad hijlim dumri gu ovwaku mot ofegeecu nemzepip rajlot tohahhew. Evuriz vo cuvsidur ci so kogmo ibammow sirujdaz gefihan dokjimbaj piozided sejozguh fumuw tip.","title":"Uv weso beg.","updatedAt":"2015-05-01T05:45:05.788Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.763Z","datetime":{"__type":"Date","iso":"2015-07-10T06:52:48.764Z"},"duration":1800000,"link":"http://uku.net/okuhaka","objectId":"g2PFwdTxs5","summary":"Picusu upwo milcumfu do apusur dotul nagit fub kabzewa ni rat nup akujif bafi vebiz uk ukogelles ajehepa. Zuhemah roivkik vu ic mipure jujawnij unume ica vug fina pabojul ucenaro ibuter palpat tughezgo ja se. Ovi tuh nupo lojejcuf unahil cif canakej osfe hiwmedhuh farusim gehkil sihbal etag tisnuri jefuf. Ewiire cog undise ilaufu so vew duawoje pa ursi bemfabhu is jarmadwis hawoh ga pukduma kuhju vakujeg co.","title":"Coz fa wawojkum.","updatedAt":"2015-05-01T05:45:05.763Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.766Z","datetime":{"__type":"Date","iso":"2015-06-25T06:21:50.103Z"},"duration":3600000,"objectId":"oQplFbI9HI","summary":"Ve mizo ku sisuhu ila pijamhi gumgifsen cikfos luwsastaw waif bo cum ho ipibik lezde wodfa vad bimij. Ta pi webco rabubjac apoficro irizi ni tecguk cef eba johlu murravca mukuhe agile sikef wij wak. Va lanzep mi olpa lol wiirve zi ewa lucvat ruob ka fudjujoka dewpof. Betejaw firpifis ow zivi awa totju bagwu nar guz dejuf pigiat le savrur na. Za irikeremi denupem wotpag no mobsosnom kumehsil jo gawi ifa fu adjogzuv sucpip ibzitra don vonugabap. Jek vude ozu to nidu biznej ompim ni vegtom po ribil cetisdun. Dur fuh sa zilob tuj havuz toucefo uzo osdengah ve hir gih fidguk halo ejaru nohzuvsib ideciba ifrijfen.","title":"Tor mocehsi voz.","updatedAt":"2015-05-01T05:45:05.766Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.765Z","datetime":{"__type":"Date","iso":"2015-04-29T11:56:12.493Z"},"duration":3600000,"link":"http://je.edu/jak","objectId":"ob4kmXpTsE","summary":"Camze vav cidoltar jat jekaf ujihva udloli do ere mel bultaane se erovkid uvuwikvo oru bueg. Kiszo teewi ga lewoefa akezoz sat dohorura sa eglo suj am agokepzi idemejel vel beg ote ovutobros. Pemtul faslar giamto nagosin vurgekur moimiloc tuz ucamid apewomnah ihesa fan hakkokag cihoupu rofkugo. Hokez ijpep hifat ujufi fu bozos sil onadibvag urzer datwem gel tioke me zuspaaj tel no ecmocnuf opa. Dosulja kuwoazo reka paipaage can katbodpo zoumofam wokokeno boghamlal rekvo wizboure lur wi. Zejovjag kizajnec acusasce gufnot edavo nan za lo zis jarfogu da pen weig icodiabo vezujpo.","title":"Re lazuzed ujfofsa.","updatedAt":"2015-05-01T05:45:05.765Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.764Z","datetime":{"__type":"Date","iso":"2015-05-22T02:49:03.830Z"},"duration":1800000,"objectId":"q2xZ6wiv1C","summary":"Gar sabkumi di rarul si hikuf zinsakdes kasefov revnij faclenud witvovdi tusaveho ik tojca. Bizu elma vegzez gojav lezu jas puffapes iluleoju uwzuwem nuce momvuw vuvi babgi unulucudo ul rizfoj livasbet kow. Evicad ukinufhe ruzetta epazuko vu mid uz levbe rucdidek zocboces suvjic imutu. Toutuga mehpuw lacacuzuj wub vallo feuva va huboma dur ur fu selkejiro sopkiih. Ikiabfi rare ato keukgim sasnu ivocaiw peczin ecumac huzebimuh vob zuhiwca isna ucuvac purvuw fogo jetka.","title":"Viefvo ci uhijekas.","updatedAt":"2015-05-01T05:45:05.764Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.784Z","datetime":{"__type":"Date","iso":"2015-05-05T07:11:03.029Z"},"duration":1800000,"link":"http://pub.edu/jiv","objectId":"qAlY38N4ln","summary":"Uf asobogec wo pefgiegu buv nuku ijuija masocwo sivutiki jat zepah ne. Bu wo joflazno ifbod fufkovref zizabosi bovcu cof ahadob gemgug jeska jikom jad sa ledwig abuiwoho. Gejgenig vejoreb cawumizu ruosedel dikpo otfid miludab davi nepip it wawulak vifri icvoze lubu fek neh ceekewo.","title":"Tesvulile tu til.","updatedAt":"2015-05-01T05:45:05.784Z"},
{"author":{"__type":"Pointer","className":"_User","objectId":"8dlJ2EJds7"},"createdAt":"2015-05-01T05:45:05.774Z","datetime":{"__type":"Date","iso":"2015-09-03T09:25:08.198Z"},"duration":3600000,"link":"http://ha.com/goiguad","objectId":"zsvJjVuyiB","summary":"Ameno jihus erhioza elevfip oreofula pugbod catreja fez losuro pafra ta uk labasa heufubik. Fakef ofuhjen harcowvup pavmoehu caiv suji jualles mompih ebawo ijeeg seve rudpic kep oje em zobela itetoc. Kune lap cuuvwi hutojbek gaslur ebmoh gohtam nacavfe cubtivow mav horu abemogu sogmedgap. Je wegeru aji fivcij fiev kiw ikrahhe wa lu jiepe kizesij imocoli jis.","title":"Tosaj kersad wisnuz.","updatedAt":"2015-05-01T05:45:05.774Z"}
],"count":10}
To provide a bit more context a RESTful call to the EventSeries:
curl -X GET \
-H "X-Parse-Application-Id: <APP_ID>" \
-H "X-Parse-REST-API-Key: <API_KEY>" \
-G \
--data-urlencode 'count=1' \
--data-urlencode 'limit=1' \
--data-urlencode 'include=event' \
https://api.parse.com/1/classes/EventSeries
Results in:
{"results":[
{"createdAt":"2015-05-01T05:45:05.963Z","events":{"__type":"Relation","className":"Event"},"objectId":"LbwZXewwjl","propagandaImageSrc":"images/something.jpg","seqId":1,"title":"Ah nubem eferifed.","updatedAt":"2015-05-01T05:45:05.963Z"}
],"count":1}
And now with a slight modification to the include parameter:
curl -X GET \
-H "X-Parse-Application-Id:<APP_ID>" \
-H "X-Parse-REST-API-Key: <API_KEY>" \
-G \
--data-urlencode 'count=1' \
--data-urlencode 'limit=1' \
--data-urlencode 'include=events' \
https://api.parse.com/1/classes/EventSeries
Results in:
{"code":102,"error":"field events cannot be included because it is not a pointer to another object"}
回答1:
After speaking with Hector from FB is seems this was a design decision, not certain exactly how using a array data-type is better than a relation (given the relation points to a single object and the array has pointers for all objects in it), so here below is the solution:
var chance = require('cloud/lib/chance/chance.js').Chance();
var Factory = require('cloud/lib/rosie/src/rosie.js').Factory;
Parse.Cloud.define("buildRelationalEvents", function(request, response) {
var EventSeries = Parse.Object.extend("EventSeries");
var Event = Parse.Object.extend("Event");
Factory.define('Event', Event)
.attr('title', function(){ return chance.sentence({words: 3}); })
.attr('datetime', function(){ return chance.date({ year: 2015, month: chance.pick([3,4,5,6,7,8,9]) }); })
.attr('duration', function(){ return chance.pick([3600000, 1800000]); })
.attr('link', function(){ return (chance.bool({likelihood: 30}) ? undefined : chance.url() ); })
.attr('summary', function(){ return chance.paragraph(); });
Factory.define('EventSeries', EventSeries)
.attr('title', function(){ return chance.sentence({words: 3}); })
.attr('propagandaImageSrc', function(){ return 'images/BTF-YOGA-SERIES-2.jpg'; });
var events = Factory.buildList('Event', chance.integer({min: 5, max: 20}) );
var query = new Parse.Query(Parse.User);
query.equalTo('username','obi.yoga');
return query.first().then(function(user){
console.log(user.get('username')+" found");
var promises = [];
events.forEach(function(event){
event.set('author', user);
promises.push(event.save());
});
return Parse.Promise.when(promises);
})
.then(function(){
var series = Factory.build('EventSeries');
// var relation = series.relation("events");
// relation.add(events);
series.set('events', events);
return series.save();
})
.then(response.success, response.error);
});
The related curl command to get parent and children:
curl -X GET \
-H "X-Parse-Application-Id: <APP_ID>" \
-H "X-Parse-REST-API-Key: <API_KEY>" \
-G \
--data-urlencode 'count=1' \
--data-urlencode 'limit=1' \
--data-urlencode 'include=events' \
https://api.parse.com/1/classes/EventSeries
来源:https://stackoverflow.com/questions/29989835/parse-com-restful-one-to-many-request-with-related-children-populated