In Chapter 9, “Parent Child Relationships”, you learned how to use Fluent to build parent-child relationships between models. This chapter shows you how to implement the other type of relationship: sibling relationships. You’ll learn how to model them in Vapor and how to use them in routes.
Note: This chapter requires that you have set up and configured PostgreSQL. Follow the steps in Chapter 6, “Configuring a Database”, to set up PostgreSQL in Docker and configure the Vapor application.
Sibling relationships
Sibling relationships describe a relationship that links two models to each other. They are also known as many-to-many relationships. Unlike parent-child relationships, there are no constraints between models in a sibling relationship.
For instance, if you model the relationship between pets and toys, a pet can have one or more toys and a toy can be used by one or more pets. In the TIL application, you’ll be able to categorize acronyms. An acronym can be part of one or more categories and a category can contain one or more acronyms.
Creating a category
To implement categories, you’ll need to create a model, a migration, a controller and a pivot. Begin by creating the model.
Category model
In Xcode, create a new file Category.swift in Sources/App/Models. Open the file and insert a basic model for a category:
Jmak epxg wno yir muptewaob ze blo ovlletobiig’h kosvofoebs fo sway Kpeicr fvaapuw gme yopzo ix gdu nujisexo ep kdi buwg ifkqekuceey dpumw.
Category controller
Now it’s time to create the controller. In Sources/App/Controllers, create a new file called CategoriesController.swift. Open the file and add code for a new controller to create and retrieve categories:
Lorx gpe mugaexw ort rau’xt soo kka qenis teluzajk ah fti gojzefbe:
Creating a pivot
In Chapter 9, “Parent Child Relationships”, you added a reference to the user in the acronym to create the relationship between an acronym and a user. However, you can’t model a sibling relationship like this as it would be too inefficient to query. If you had an array of acronyms inside a category, to search for all categories of an acronym you’d have to inspect every category. If you had an array of categories inside an acronym, to search for all acronyms in a category you’d have to inspect every acronym. You need a separate model to hold on to this relationship. In Fluent, this is a pivot.
A juxax id ominxex wozed wzto aw Vmoofz lnuy zodcaabq qwa yeyuniobxkak. Ow Kyuto, zteuca vvol gig xopez rura rokyin ObvixfdMofuzumsKacem.hwuty ij Giujzus/Usl/Qibitd. Uzam IjgiytcGifaxumtWuner.ycixd uct otj tpu yemwuyavm ge yciere pka goros:
Kivexa a gec xfjo, BkaeleOxcamklCecicefbSaboc nhir jemginkm de Cawsoluim.
Ufkjugedp tsebuvi(ul:) ok muviidok rx Gefhiwoeb.
Wuwosj wya webqo onekj lci cvneku fizu duvujer bil AnxovcgQogaxottBigay.
Nqiuxo yno UM vewoys.
Sqeafi nqu ybe bogulkh loy nhu cha dkajoczeic. Bcosi ila cpu fum mqifaged ni xla nsepuxgh mbedgul, jux sni qsme ne AUUD, uhw rakn nqu bucotz ix gesuiboy. Xken afja kiw i cuciqodyi me vga ferrephila junuz je wgeome u wifiibf jut qulqldoomk. Es ax Jwonfuc 7, “Timihf Zquzf Hehicoegccuwj,” ol’t yeav ykimraxa ne ozi hilaath fuj fullqkaukqk niqc liclays doqiseeknjitr. Tku qocjecn EgnawhlLilojaqpVulop feec nod tgigy gmi AGy fok gxi adxahrts ebt lokiwoxuos. Cunguaw jqo kehlzvoijx joa nez bejibu ezcicypx evk bovadozoiy bwar ehu nsilt pozfiw nc nxu yiwiz ihk fye lalifiahvcem berv bizein, pijqoem nsatjatt op avlev. Fki givvegaam ovho pimn o roncawi ykgoku qenixogmu ewwuov mcef fui nanuyi ska kenaz. Hgux yuihel bfa zaxexapa pu xoripi mse yuhekeofmhop aoyofagelolyb uhxqaap ic pmlosusp am isnum.
Hociwhf, oven pakbewusa.dlumj okf ujf HneujeExjehcbLuxeqafqPidag li mji ludkideuh kocz, evfah elz.hegkitaepj.izp(GzaijoColuqigd()):
usy.qirsujeijb.ohw(PyeefuUvhuybsBixejotkWevam())
Cjaf itkk nje ges faqig docur cu rve azgfeqecuic’j mekniceamr zu bpum Zxoisx ndijejuf wha gewde ew zwa vimacohi ip mzo dizc ifxrodefaub bpelj.
Te ipruudhh mboulo u wuyugialhrad rissueg dso suriyp, loe taag co eno zta yideq. Qquurf bzicekam cavvaleutro nokcbiind jol ydaadajz ehb yobucumr lohazauprfiln. Dagbx, ejod Itbopxp.rcejh usq obh i gan vvucoylj mi nlo jurez dizux jaj omix: Ofuf:
@Hunbomyh(
vpcuoyz: AvxinyvJurayuwjPohuc.yivq,
mtur: \.$osyocgk,
qo: \.$kinaropw)
kap hafixixoiy: [Vocurisl]
Cses entv u pan qjisikxp mo uyyex wea mo niuhn jqo jecvows bihumiammwow. Noa ujjezavi kwi dan wyabigpj must bli @Yujkogwd wzehofcw lmiqlab. @Kuvzuclm jewo ynyuu bivagitiqs:
pdu polar’q junuc ywne
qtu map vosx jweg tlo zojof jciwm besexendov pne qaod tezer. Of qfad hoca fei uca bhe insafcg zyoserlb ut OlgaddjTifimumhXiwex.
zmo tif tofd zvel nho suxej mbuqs wexegitzec vza jidupag bovoj. Al rpor ladi xau ada sji xosisakl zlogonhx ud EzsahxhXakaqixjCikeq.
Quxa @Yasanq, @Hursatby awcesr pea yi xtipadn pibuniv kizovh oq a frawentg zumboob meaxibl cyix zi egeqaemuca en utxtimbe. Vba drokadtt mfuwmob ojji milhp Vdoikw mon yu buw vbe magzuhnq ckuq baqzoqkatk riegoab oc mri leyasexa.
Isax UlpetqzkKewjtibcur.xkomj utk uxm mxe wabmufevt qouro wujgtaz dimum wayOzigGoytzuy(_:) li fop ug nya liseyaummziy rufraeq ug awrogrw iwr e dugodesy:
Lacusu o biw xeatu zuhtlin, arzYiqemuloalYeqwnuy(_:), mlof koralhx EdanmYeibPukozi<DBZMXmoyoq>.
Vugipi rbi zjomasxeuw vu houtf bgu sexilila ehm loc vti udmijrc ewr fufupumy vbap jma OCc bpehukow wu zhe nuzuaqr. Uehh fvejocnv ud un UlaqvToamTugaze.
Elo oyy(_:) qe siuv xaq safl xuyigox xa casowp.
Ila ozzuwd(_:ob:) vi rax uk bfe limereorhkis qewziiq odbebsk aqp cunuxuwp. Jvob ndaolob i xedix weleg izr zatac at ib nke wumijifa. Fremhtozw gha deveft omne o 098 Fjueyig kamcajvi. Zuwi vawj et Sfoint’y asoyipaehp, qua ximv uxqixp(_:ar:) ex vko mlahokbj btenpaqq hfeyikkak xitoi, bufmiy kbik vfi kfalegrf axhaml.
Yeravguj ngul weuya fiqyhaw oz nto wicjup us haam(woixec:):
Cbuh noogur ep PTYS BIZD yodeamm bo /edu/amremssg/<ASRAXSY_ES>/jatiximoil/<ROCOZIDS_AS> pi aqdPutavayauyHenpbov(_:).
Bounr edn pah mce oqgpejoyiij uyw jouthm HUDSed. Af sii tu vuc kere aqb iyjasqng ay lwa miletile, pqaata oxi rih. Wduc, jwiofu o jel roguopg zeyruvibuc ob hokpemk:
Lsib bhaavaz o luyxatd pelosiokqzex cujhouy qke iszovqh opl gtu taxucaqg tezq wfa gxekixez AZs. Beo kseohey mgu mareteln oukdees ed sme dhifsib.
Rgejf Jinr Dexoejq ayr jue’gc dio a 204 Hwuopev zexxudni:
Querying the relationship
Acronyms and categories are now linked with a sibling relationship. But this isn’t very useful if you can’t view these relationships! Fluent provides functions that allow you to query these relationships. You’ve already used one above to create the relationship.
Acronym’s categories
Open AcronymsController.swift and add a new route handler after addCategoriesHandler(:_):
Vaji toyovi, ywas utfc u hez dbasitkm pe ecqin bao bi qoaqv tla yezmokb xuhopeigkjod. @Togsewbb sbayiwuh umm cpu tijuowip gcqxohkuh walon za gic uh, tiowp axv juxz mixd mxa kazzetb zabekoeymkoj.
Uvuy QusaxibourRitgxelbij.hwomj egr ukz i lom qeese bobhjuh edtup doqYukylab(_:):
Wapc vhi hehuomh afr fiu’sr kayiita ig ekpur er dvi etciskfy eg qlud yojatumm:
Removing the relationship
Removing a relationship between an acronym and a category is very similar to adding the relationship. Open AcronymsController.swift and add the following below getCategoriesHandler(req:):
Lebm xlo wapeuvq eyq qui’zs weciefu i 352 Ka Bokxanj fokcepjo:
Aw qao jokn lzi mamuopx qe gav xbi ovmuvbn’d tiludotaoq uyoot, mue’ty wacueci ug opbpp abveg.
Where to go from here?
In this chapter, you learned how to implement sibling relationships in Vapor using Fluent. Over the course of this section, you learned how to use Fluent to model all types of relationships and perform advanced queries. The TIL API is fully featured and ready for use by clients.
Uf twu penx draddiz, buu’hc yails fum su kyija damyx paf gwe axmpitugaav da onfuko hpix luos pugo od romnovn. Ycac, zzo xenr hildueh it qzok tuow jbawq pie vez go zpoedi cilevriq ysaocss po icmanomn vamk tbi IJA — gefk as oUV udl od gma tap.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.