【问题标题】:How get sum of field in the related table in one query in Yii2如何在 Yii2 的一个查询中获取相关表中的字段总和
【发布时间】:2015-02-07 12:38:12
【问题描述】:

大家, 我有 2 个表,通过第三个相关: 结构如下:

Playlist: id, channel_id, name, date
Files: id, name, duration
Playlist-rel-Files: list_id, file_id

我在我的应用程序中使用 ActiveRecord。当我使用此类查询获取最后一个播放列表时:

$pl = Playlist::find()
                ->where(['channel_id' => $model->channel_id])
                ->orderBy(['date' => SORT_DESC])
                ->limit(1)
                ->one();

然后我使用这样的代码来获取与最后一个播放列表相关的所有文件:

$f = $pl->files;

一切正常,我得到了文件数组,但我不需要它们的列表,我只需要文件持续时间的总和,要获得这个总和,我需要在 foreach 中运行数组,我的问题是:

如何修改我的第一个查询以在一个查询中获取播放列表数据和此播放列表文件的持续时间总和?有可能吗?

【问题讨论】:

    标签: mysql activerecord yii2


    【解决方案1】:

    您正在寻找的是一个统计查询。您可以为您的计数定义一个新关系,例如

    public function getFileCount() {
        return $this->hasMany(Files::className(), ['id' => 'file_id'])
                    ->viaTable('playlist-rel-files', ['playlist_id' => 'id'])
                    ->sum('duration');
    }
    

    然后可以使用魔术属性$fileCount 访问它,并且可以通过with 将其添加到查询中以进行即时加载,即:

    $pl = Playlist::find()
                ->with('fileCount')
                ->where(['channel_id' => $model->channel_id])
                ->orderBy(['date' => SORT_DESC])
                ->one();
    

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多