Server Side Swift with Vapor - Part 12: Parent-Child | Ray Wenderlich

Learn how to set up parent-child relationships in Fluent and how to query models for the parent-child relationships.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4493-server-side-swift-with-vapor/lessons/12

It took me a while to wrap my head around this one! Is there a reason why the Parent struct takes in <Child, Parent> and then the Children struct takes in <Parent, Child>? I’m sure there is a reason. Could it be how you are saying it out loud as you write it?

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@simonqq it’s to do with the way it reads (it should follow the Swift Style Guide). Basically it’s the Parent object for Children of Parent, whereas the Children is Parent of Child - make sense?

@0xtim Awesome! Makes perfect sense.

1 Like

I mimic’d what you taught us here and created an Order class that has a Station as a parent:

final class Order: Codable, PostgreSQLModel, Content, Migration {
    var stationID: Station.ID

    var station: Parent<Order, Station> {
        return parent(\.stationID)
    }
}

After running my app and looking at the database config, the table that’s created just defines stationID as a bigint but there are no foreign key relationships setup to the other table. Did I miss a piece here?

@gargoyle no you haven’t missed anything - there wasn’t time in the videos to cover it. Fluent manages the relationship for you. To set up foreign key constraints you need to change your migration, something like https://github.com/raywenderlich/vapor-til/blob/master/Sources/App/Models/Acronym.swift#L63

Quit slacking and get that book out :smirk:. Thanks for the sample!

@0xtim I’m just completely stuck on how to use the Children property to get my data out and use it immediately. Any chance you can answer this question at stackoverflow?

@simonqq I can’t ever remember the order based on the naming, but I found it’s easier to just think that no matter which you use, the current class type always goes first, and then the referenced class goes second.

@gargoyle I’ve answered!