I'm trying to setup an association between songs and albums. Each song can appear on one or more albums and each album can contain one or more songs. I decided to go with GRDB for my database solution but I'm stuck on this issue.
What I tried:
As documentation suggests, I created a passport struct, like this:
public struct AlbumPassport: TableRecord {
static let track = belongsTo(SPTTrack.self)
static let album = belongsTo(SPTAlbum.self)
}
Then in SPTTrack class:
public static let passports = hasMany(AlbumPassport.self)
public static let albums = hasMany(SPTAlbum.self, through: passports, using: AlbumPassport.album)
And in SPTAlbum class:
public static let passports = hasMany(AlbumPassport.self)
public static let tracks = hasMany(SPTTrack.self, through: passports, using: AlbumPassport.track)
I cannot find in the documentation a good example on how to build a request using those associations. In SPTAlbum class I added linkedTracks property
public var linkedTracks: QueryInterfaceRequest<SPTTrack> {
request(for: Self.tracks)
}
And then in my database manager:
func fetchTracks(for album: SPTAlbum) -> [SPTTrack] {
do {
return try dbQueue.read { db in
try album.linkedTracks.fetchAll(db)
}
} catch {
print(error)
}
return []
}
I'm getting error:
SQLite error 1: no such table: albumPassport
which is pretty self-explanatory, but I have no clue how and where should I create table for the AlbumPassport struct and if there are any additional steps I should take to actually populate this table with album/track connections.
Both SPTTrack/SPTAlbum have a field called id which is set as primaryKey during first migration.
There are no issues with your associations. All
hasMany()andbelongsTo()are correct. The error you are getting tells me that there is something wrong with your database setup (which you didn't include in your question).Here is how i would implement it:
See my answer of Many-to-many relationship where one entity has multiple properties of the same type for another code example.