2

我正在尝试在歌曲和专辑之间建立关联。每首歌可以出现在一个或多个专辑中,并且每个专辑可以包含一首或多首歌曲。我决定为我的数据库解决方案使用GRDB,但我被困在这个问题上。

我尝试了什么:正如文档所示,我创建了一个passport结构,如下所示:

public struct AlbumPassport: TableRecord {
    static let track = belongsTo(SPTTrack.self)
    static let album = belongsTo(SPTAlbum.self)
}

然后在 SPTTrack 类中:

public static let passports = hasMany(AlbumPassport.self)
public static let albums = hasMany(SPTAlbum.self, through: passports, using: AlbumPassport.album)

在 SPTAlbum 类中:

public static let passports = hasMany(AlbumPassport.self)
public static let tracks = hasMany(SPTTrack.self, through: passports, using: AlbumPassport.track)

我在文档中找不到关于如何使用这些关联构建请求的好例子。在 SPTAlbum 类中,我添加了linkedTracks属性

public var linkedTracks: QueryInterfaceRequest<SPTTrack> {
    request(for: Self.tracks)
}

然后在我的数据库管理器中:

func fetchTracks(for album: SPTAlbum) -> [SPTTrack] {
    do {
        return try dbQueue.read { db in
            try album.linkedTracks.fetchAll(db)
        }
    } catch {
        print(error)
    }
    return []
}

我收到错误:

SQLite 错误 1:没有这样的表:albumPassport

这是不言自明的,但我不知道应该如何以及在哪里为AlbumPassport结构创建表,如果有任何其他步骤我应该采取实际使用专辑/曲目连接填充此表。

SPTTrack/SPTAlbum 都有一个名为的字段,该字段在第一次迁移期间id设置。primaryKey

4

1 回答 1

2

您的关联没有问题。所有hasMany()belongsTo()都是正确的。您收到的错误告诉我您的数据库设置有问题(您的问题中没有包括)。

这是我将如何实现它:

架构

import GRDB

struct Album: Codable, Hashable, FetchableRecord, MutablePersistableRecord {
    mutating func didInsert(with rowID: Int64, for column: String?) { id = rowID }
    var id: Int64?
    var name: String
    static let passports = hasMany(AlbumPassport.self)
    static let tracks = hasMany(Track.self, through: passports, using: AlbumPassport.track)
}

struct Track: Codable, Hashable, FetchableRecord, MutablePersistableRecord {
    mutating func didInsert(with rowID: Int64, for column: String?) { id = rowID }
    var id: Int64?
    var name: String
    static let passports = hasMany(AlbumPassport.self)
    static let albums = hasMany(Album.self, through: passports, using: AlbumPassport.album)
}

struct AlbumPassport: Codable, Hashable, FetchableRecord, PersistableRecord {
    let track: Int64
    let album: Int64
    static let track = belongsTo(Track.self)
    static let album = belongsTo(Album.self)
}

let queue = DatabaseQueue()
try queue.write { db in
    
    try db.create(table: "album") { t in
        t.autoIncrementedPrimaryKey("id")
        t.column("name", .text).notNull()
    }
    try db.create(table: "track") { t in
        t.autoIncrementedPrimaryKey("id")
        t.column("name", .text).notNull()
    }
    try db.create(table: "albumPassport") { t in
        t.column("track", .integer).notNull().indexed().references("track")
        t.column("album", .integer).notNull().indexed().references("album")
        t.primaryKey(["track", "album"])
    }
    
    // Testing real data from https://music.apple.com/de/artist/yiruma/73406786
    
    var solo = Album(name: "SOLO")
    try solo.insert(db)
    var sometimes = Track(name: "Sometimes Someone")
    try sometimes.insert(db)
    try AlbumPassport(track: sometimes.id!, album: solo.id!).insert(db)
    var destiny = Track(name: "Destiny Of Love")
    try destiny.insert(db)
    try AlbumPassport(track: destiny.id!, album: solo.id!).insert(db)
    
    var bestOf = Album(name: "Best of Yiroma")
    try bestOf.insert(db)
    var poem = Track(name: "Poem")
    try poem.insert(db)
    try AlbumPassport(track: poem.id!, album: bestOf.id!).insert(db)
    var river = Track(name: "River Flows In You")
    try river.insert(db)
    try AlbumPassport(track: river.id!, album: bestOf.id!).insert(db)
}

// Fetch all albums and their tracks
try queue.read { db in
    struct AlbumInfo: FetchableRecord, Decodable, CustomStringConvertible {
        var album: Album
        var tracks: Set<Track>
        var description: String { "\(album.name) → \(tracks.map(\.name))" }
    }
    let request = Album.including(all: Album.tracks)
    let result = try AlbumInfo.fetchAll(db, request)
    print(result)
    // > [SOLO → ["Sometimes Someone", "Destiny Of Love"], Best of Yiroma → ["River Flows In You", "Poem"]]
}

对于另一个代码示例,请参阅我对多对多关系的回答,其中一个实体具有多个相同类型的属性。

于 2021-09-29T04:15:17.353 回答