是否可以在GET请求中返回流利的孩子?

时间:2019-09-07 18:02:32

标签: mysql swift vapor

现在我有以下两个课程:

final class Song: MySQLModel {
    var id: Int?
    var lyrics: String
    var artist: String
    var title: String
    var strummingPattern: String

    init(id: Int? = nil, title: String, lyrics: String, artist: String, strummingPattern: String) {

        self.id = id
        self.lyrics = lyrics
        self.title = title
        self.artist = artist
        self.strummingPattern = strummingPattern

    }
}

extension Song {
    var chords: Children<Song, SongChord>{
        return children(\.songID)
    }
}

final class SongChord: MySQLModel {
    var id: Int?
    var songID: Int
    var chord: String
    var position: Int

    init(id: Int? = nil, chord: String, position: Int, songID: Int) {
        self.songID = songID
        self.id = id
        self.chord = chord
        self.position = position
    }
}

extension SongChord {
    var chords: Parent<SongChord, Song>{
        return parent(\.songID)
    }
}

我想返回所有Song及其子SongChord的列表。到目前为止,我想出了:

return Song.query(on: req)
            .join(\SongChord.songID, to: \Song.id)
            .alsoDecode(SongChord.self)
            .all()

但是这将返回错误“无法将类型'EventLoopF​​uture <[((Song,SongChord)] >>)的值转换为结束结果类型'_'”。网上有些人建议做平面图,但这仍然会产生错误。关于如何找回孩子的任何建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

由于错误提示您返回exec:rev。如果您从EventLoopFuture<[(Song, SongChord)]>解码多个模型,则每个结果行将收到query resultSong的Tupel;您现在要做的是:

  1. 创建一个结构(例如SongChord),该结构符合SongViewModel并具有Content和另一个称为Song的变量的所有相关字段。原因是,原始的chords: [SongChords]模型没有Song的数组,而只有SongChord的数组,您无法轻松地解析
  2. Children<Song, SongChord>Map[(Song, SongChord)]的结果。这可能对您转换元组数组很有帮助:https://stackoverflow.com/a/31220067/710350
  3. 返回[SongViewModel]