首页 > 解决方案 > Laravel 聚合 eloquent 最大结果

问题描述

这是我正在尝试做的事情:

我正在我的供应商表中实现一个 version_id。我正在尝试构建一个查询以使索引页面正常工作。因此,我希望从我的数据库中获取所有具有最新 version_id (max('version_id') 的供应商。似乎无法弄清楚。这是我到目前为止所拥有的:

$vendors = $this->account->vendors()->where('version_id', max(version_id))

        ->orderBy($this->orderBy, $this->sortBy)
        ->paginate($this->display_per_page);

我以前试过这个,但它也给了我错误:

$vendors = $this->account->vendors()->max('version_id')

            ->orderBy($this->orderBy, $this->sortBy)
            ->paginate($this->display_per_page);

如果我有这个就可以了:

$vendors = $this->account->vendors()
            ->orderBy($this->orderBy, $this->sortBy)
            ->paginate($this->display_per_page);

一直在网上寻找,但我只找到关于连接等查询的建议,这不是我想要的。任何帮助表示赞赏!

标签: phpmysqllaraveleloquent

解决方案


这应该有效:

$vendors = $this->account->vendors()
    ->whereRaw('version_id = (SELECT MAX(version_id) from vendors)')
    ->orderBy($this->orderBy, $this->sortBy)
    ->paginate($this->display_per_page);

假设表名vendors


推荐阅读