关系字段上的 TypeORM SUM 运算符

zet*_*tee 5 mysql typeorm nestjs

我是一名学生,试图开发一个音乐库,只是为了尝试新技术。

目前我使用 NestJS 和 TypeORM 作为我的后端技术(以及 MySQL 数据库)。

我想实现什么目标?我想获取播放列表的总持续时间。因此,一个播放列表由许多歌曲组成,并且歌曲可以出现在多个播放列表中。所以此时我们就有了多对多的关系。现在,为了获取totalDuration,我认为使用某种SUM运算符是一个好主意。这正是我的问题:我将如何使用 TypeORM 做到这一点?

我尝试了以下查询构建器:

const playlist = await this.playlistRepository.createQueryBuilder("playlist")
        .where("playlist.id = :playlistId", { playlistId })

        // This is for relations
        .leftJoinAndSelect("playlist.author", "author")
        .leftJoinAndSelect("playlist.artwork", "artwork")
        .leftJoinAndSelect("playlist.collaborators", "collaborators")
        .leftJoin("playlist.songs", "songs")

        // Counting the songs
        .loadRelationCountAndMap("playlist.songsCount", "playlist.songs")

        // SUM up the duration of every song to get total duration of the playlist
        .addSelect('SUM(songs.duration)', 'totalDuration')
        .groupBy("playlist.id")
        .getOne()
Run Code Online (Sandbox Code Playgroud)

但这给了我一个我不知道如何解决的错误:

QueryFailedError: Expression #16 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'soundcore_dev.collaborators.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Run Code Online (Sandbox Code Playgroud)

由 TypeORM 构建的结果查询如下所示:

QueryFailedError: Expression #16 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'soundcore_dev.collaborators.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Run Code Online (Sandbox Code Playgroud)

我只做了一些研究,发现了如何使用 typeORM 进行总结,但我没​​有让它为我工作。上面的代码等等就是我找到的一切。我想我只是错过了一些非常重要的东西......

也许有人可以在这一点上支持我。我真的很感激这一点。祝你有美好的一天!并提前感谢您的支持。

You*_*uba 11

读完你的问题后,我不确定你为什么要加载所有关系并按播放列表 id 对它们进行分组,
无论如何,你需要知道的第一件事是我们何时想要获取sum,max,avg,..我们使用的getRawOnegetRawMany

对于您的查询,您只需要执行以下操作:

const playlist = await this.playlistRepository.createQueryBuilder("playlist")
    .where("playlist.id = :playlistId", { playlistId })

    // This is for relations
    .leftJoin("playlist.songs", "songs")

    // Counting the songs
    //.select('COUNT(songs.id)', 'numbersongs') in case you want count of songs

    // SUM up the duration of every song to get total duration of the playlist
    .addSelect('SUM(songs.duration)', 'totalDuration')
    .getRawOne()
Run Code Online (Sandbox Code Playgroud)