You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel关联查询求助:获取带最新日志点赞总和的TikTokAccount

解决方案

首先纠正几个核心问题:

  • 原代码里的lastestPostLog是拼写错误,需改为latestDailyLog(假设你的Post模型中关联最新日志的方法名为此)
  • withCount用于统计关联记录数量,不能直接嵌套withSum,需通过子查询或关联查询实现「每个Post的最新日志views_24h总和」的需求

步骤1:完善Post模型关联

先在Post模型中定义获取单条最新日志的关联:

// app/Models/Post.php
public function latestDailyLog()
{
    return $this->hasOne(Dailylog::class)->latest('created_at'); // 按创建时间取最新日志
}

步骤2:两种可行的查询写法

写法一:用withSum结合子查询(保持Eloquent风格)

TikTokAccount::whereHas('accountStat')
    ->with(['accountStat'])
    ->withSum(['postedVideos' => function ($postQuery) {
        // 给每个Post追加最新日志的views_24h字段,再对该字段求和
        $postQuery->addSelect([
            'latest_views' => Dailylog::select('views_24h')
                ->whereColumn('post_id', 'posts.id')
                ->latest('created_at')
                ->limit(1)
        ])->selectRaw('SUM(latest_views) as aggregate');
    }])
    ->limit(5)
    ->get();

查询结果会包含posted_videos_sum字段,即该账号所有Post最新日志的views_24h总和。

写法二:用子查询关联(大数据量下性能更优)

use Illuminate\Support\Facades\DB;

TikTokAccount::whereHas('accountStat')
    ->with(['accountStat'])
    // 关联每个Post的最新日志子查询
    ->leftJoinSub(
        Dailylog::select('post_id', 'views_24h')
            ->whereIn('id', function ($subQuery) {
                $subQuery->select(DB::raw('MAX(id)'))
                    ->from('dailylogs')
                    ->groupBy('post_id');
            }),
        'latest_logs',
        'posts.id',
        '=',
        'latest_logs.post_id'
    )
    // 关联Post表
    ->join('posts', 'tiktok_accounts.id', '=', 'posts.tiktok_account_id')
    // 求和并处理无日志的情况
    ->select('tiktok_accounts.*', DB::raw('COALESCE(SUM(latest_logs.views_24h), 0) as total_latest_views'))
    ->groupBy('tiktok_accounts.id')
    ->limit(5)
    ->get();

COALESCE用于处理账号无日志的场景,避免返回null值。

原代码问题说明

  • withCount的闭包逻辑错误:它的作用是修改关联计数的查询规则,不能直接调用withSum
  • 未筛选每个Post的最新日志:原写法会把该Post的所有日志views_24h累加,不符合需求

内容的提问来源于stack exchange,提问作者Shoaib ALi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:52:54