【问题标题】:Laravel - How to Sum relative table with limit result?Laravel - 如何将相对表与限制结果相加?
【发布时间】:2020-06-04 12:46:39
【问题描述】:

我有这两个模型。

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

如何使用 Query Builder 或 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'];
}

【问题讨论】:

    标签: php laravel eloquent laravel-query-builder


    【解决方案1】:

    我假设您的表格结构是:

    对于 youtube_channel_insights 的表,您拥有:

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

    对于 youtube_video_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();
    

    【讨论】:

    • 问题是我想得到限制 12 个结果的总和 limit(12)。我的表的结构是正确的,但我不明白代码中的 TotalCatch 或 TotalCatches 是什么
    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2017-10-06
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多