Embedding parent relation

Is it possible to fetch child then fetch parent relation and put in the custom Content model with both parent and child type? And how to register in router with controller?

@pyae sure, you can nest your futures and pull out relations after you get each part. Putting into into a custom Content type is easy once you have anything. Registering with a controller depends on what things you need (such as parameters).

Take a look at vapor-til/WebsiteController.swift at main · raywenderlich/vapor-til · GitHub as an example. This returns Future<View>, but there’s no reason why you couldn’t just change that to UserContext and make UserContext conform to Content - make sense?

@0xtim Thanks for reply and pointing out what I am missing from the book.

return Planet.query(on: req).all().flatMap(to: [SuperGalaxy].self) { planets in
	for planet in planets {
		let galaxy = planet.galaxy.get(on: req)
		let superGalaxy = superGalaxy(galaxy: galaxy, planet: planet)

and I don’t know how to convert array instance of SuperGalaxy to Future

struct SuperGalaxy: Content {
	var galaxy: Future<Galaxy>
	var planet: Planet

and that model of Content does not conform to protocol Decodable

return Planet.query(on: req).all().flatMap(to: [SuperGalaxy].self) { planets in
	var superGalaxies = [Future<SuperGalaxy>]()
	for planet in planets {
		superGalaxies.append(planet.galaxy.get(on: req).map(to: SuperGalaxy.self) { galaxy in
			return SuperGalaxy(galaxy: galaxy, planet: planet)
	return superGalaxies.flatten(on: req)

Courtesy of @anthness and me because he typed from the phone and got typos. Hope this would help someone someday :star2:

1 Like

Nice work! Glad you fixed it