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

Laravel Eloquent聚合查询:获取vendors表最新version_id记录

解决方法:获取供应商最新版本数据的Eloquent查询

你原来的代码问题出在max(version_id)这里——你误用了PHP的max()函数,它没法识别SQL字段名,自然没法从数据库里拿到真正的最大version_id值。下面分两种常见场景给你正确的写法:

场景1:获取当前账户下最大version_id的所有供应商记录

如果你的需求是拿到当前账户下所有版本号最高的供应商记录(比如所有供应商都更新到了同一个最高版本,要把这些都列出来),可以先查询出最大版本号,再筛选:

// 先获取当前账户下供应商的最大version_id
$maxVersion = $this->account->vendors()->max('version_id');

// 再筛选出对应版本的供应商并分页
$vendors = $this->account->vendors()
    ->where('version_id', $maxVersion)
    ->orderBy($this->orderBy, $this->sortBy)
    ->paginate($this->display_per_page);

或者用子查询一步完成,避免两次数据库请求:

$vendors = $this->account->vendors()
    ->where('version_id', function ($query) {
        // 子查询获取当前账户下的最大version_id
        $query->selectRaw('MAX(version_id)')
            ->from('vendors')
            ->where('account_id', $this->account->id);
    })
    ->orderBy($this->orderBy, $this->sortBy)
    ->paginate($this->display_per_page);

场景2:获取每个供应商主体的最新版本记录

如果你的vendors表是同一个供应商有多条版本记录(比如用vendor_code或original_id区分同一个供应商的不同版本),需要拿到每个供应商的最新版本,推荐用MySQL 8.0+支持的窗口函数:

$vendors = $this->account->vendors()
    ->selectRaw('*, ROW_NUMBER() OVER (PARTITION BY vendor_code ORDER BY version_id DESC) as rn')
    // 只保留每个供应商的第一条(即最新版本)
    ->having('rn', 1)
    ->orderBy($this->orderBy, $this->sortBy)
    ->paginate($this->display_per_page);

注意:把上面的vendor_code换成你表中用来区分同一个供应商的字段(比如vendor_id或者其他唯一标识)。

如果你的MySQL版本较低不支持窗口函数,可以用子查询关联的方式:

$vendors = $this->account->vendors()
    ->whereIn('id', function ($query) {
        $query->selectRaw('MAX(id)')
            ->from('vendors')
            ->where('account_id', $this->account->id)
            // 按供应商唯一标识分组,取每个组里最新版本对应的id
            ->groupBy('vendor_code');
    })
    ->orderBy($this->orderBy, $this->sortBy)
    ->paginate($this->display_per_page);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:41:44