表格数据源非 Model 的时候,在导出 Excel 的时候,查询参数需要做一下处理,否则导出的时候无法获得正确的数据。

拿原文档中的示例来说,下面新增了2个条件判断 if ($model->filter()->input('_export_'))

<?php
namespace App\Admin\Repositories;

use Dcat\Admin\Grid;
use Dcat\Admin\Repositories\Repository;
use Illuminate\Pagination\LengthAwarePaginator;

class ComingSoon extends Repository
{
    protected $api = 'https://api.douban.com/v2/movie/coming_soon';

    /**
     * 定义主键字段名称 
     * 
     * @return string
     */
    public function getPrimaryKeyColumn()
    {
        return '_id';
    }

    /**
     * 查询表格数据
     *
     * @param Grid\Model $model
     * @return LengthAwarePaginator|array
     */
    public function get(Grid\Model $model)
    {
        // 当前页数
        $currentPage = $model->getCurrentPage();
        // 每页显示行数
        $perPage = $model->getPerPage();

        //+++++++++++++++++++++++++++++++++++++++++++++++++++
        // 导出数据的时候,不能使用model中的翻页参数
        if ($model->filter()->input('_export_')) {
            $data = explode(':', $model->filter()->input('_export_'));
            $scope = $data[0] ?? '';
            $args = $data[1] ?? '';

            // 导出选择的行
            if ($scope == Grid\Exporter::SCOPE_SELECTED_ROWS) {
                $selected = explode(',', $args);
                // TODO 补充导出选择行的逻辑,如 $query->whereIn('id', $selected)
            }
            // 导出全部或当前页
            if (in_array($scope, [Grid\Exporter::SCOPE_ALL, Grid\Exporter::SCOPE_CURRENT_PAGE])) {
                $item = $model->getQueries()->last(function ($item) {
                    return isset($item['method']) && $item['method'] == 'forPage';
                });
                $currentPage = $item['arguments'][0];
                $perPage = $item['arguments'][1];
            }
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++

        // 获取排序字段
        [$orderColumn, $orderType] = $model->getSort();

        // 获取"scope"筛选值
        $city = $model->filter()->input($model->filter()->getScopeQueryName(), '广州');

        // 如果设置了其他过滤器字段,也可以通过“input”方法获取值,如:
        $title = $model->filter()->input('title');
        if ($title !== null) {
            // 执行你的筛选逻辑

        }

        $start = ($currentPage - 1) * $perPage;

        $client = new \GuzzleHttp\Client();

        $response = $client->get("{$this->api}?{$this->apiKey}&city=$city&start=$start&count=$perPage");
        $data = json_decode((string)$response->getBody(), true);

        //+++++++++++++++++++++++++++++++++++++++++++++++++++
        // 导出数据的时候,直接返回数组结果
        if ($model->filter()->input('_export_')) {
            return $data['subjects'] ?? [];
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++

        return $model->makePaginator(
            $data['total'] ?? 0, // 传入总记录数
            $data['subjects'] ?? [] // 传入数据二维数组
        );
    }

}