Php Laravel-如何将相对表与极限结果相加?
我有这两种型号 我想在Php Laravel-如何将相对表与极限结果相加?,php,laravel,eloquent,laravel-query-builder,Php,Laravel,Eloquent,Laravel Query Builder,我有这两种型号 我想在youtube\u video\u insights表中获得12列comment\u count的总和 我如何使用查询生成器或Eloquent做到这一点 我尝试在我的存储库中使用类似的东西,但没有成功 它只是将所有注释计数列相加 $this->youtube_channel_insight ->join('youtube_video_insights',function ($q){ $q->on('y
youtube\u video\u insights
表中获得12列comment\u count
的总和
我如何使用查询生成器或Eloquent做到这一点
我尝试在我的存储库中使用类似的东西,但没有成功
它只是将所有注释计数
列相加
$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();
我假设您的表的结构是:
对于youtube\u channel\u insights的表格,您有:
id | name
----------------------------------------
1 | channel_01
2 | channel_02
对于youtube\u video\u insights的表格,您有:
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();
问题是我想得到limit 12结果的总和limit(12)
。我的表的结构是正确的,但我不理解代码中的TotalCatch或TotalCatch是什么
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();