Laravel - 如何将相对 table 与极限结果相加?

Laravel - How to Sum relative table with limit result?

我有这两个型号。

我想得到 youtube_video_insights table 中 12 列 comment_count 的总和。

如何使用查询生成器或 Eloquent。

我尝试在我的存储库中使用类似的东西,但它没有用。

它只是对所有 comment_count 列求和。

$this->youtube_channel_insight
            ->join('youtube_video_insights',function ($q){
                $q->on('youtube_channel_insights.id','=','youtube_video_insights.youtube_channel_insight_id')
                    ->orderBy('youtube_video_insights.id','desc')
                    ->limit(12);
            })
            ->where('youtube_channel_insights.id',$id)
            ->select(\DB::raw(
                "SUM(youtube_video_insights.comment_count) as total_comment"
            ))->get();
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeChannelInsight extends Model
{
    protected $guarded = ['id'];

    public function videos()
    {
        return $this->hasMany(YoutubeVideoInsight::class);
    }
}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class YoutubeVideoInsight extends Model
{
    protected $guarded = ['id'];
}

我假设你的 table 的结构是:

对于 youtube_channel_insights 的 table 你有:

id | name
----------------------------------------
1  | channel_01
2  | channel_02

对于 youtube_video_insights 的 table 你有:

id | channel_id|    name    | comment_count
----------------------------------------
1  |     1     |  video_01  |      20
2  |     1     |  video_02  |      40
3  |     2     |  video_03  |      5
4  |     2     |  video_04  |      15

现在您应该像这样编写查询:

$sub1 = YoutubeVideoInsight ::select('comment_count', 'channel_id')
->whereRaw('channel_id = 2')->orderBy('id', 'Desc')->limit(2);

$sub2 = DB::table(DB::raw("({$sub1->toSql()}) as sub"))
->select(DB::raw('
SUM(`comment_count`) AS total_comment,
channel_id
'));


return $query = YoutubeChannelInsight ::joinSub($sub2,'sub2',function($join){
$join->on('channels.id','=','sub2.channel_id');
})->get();