雄辩的数据表不应用于where(),orderBy()等

时间:2017-05-11 06:25:13

标签: php datatable eloquent

我编写了一个类,它采用一个Eloquent模型并对其进行操作,以便为datatable输出JSON。数据表通过POST请求使用服务器端处理。

这是班级:

namespace App\Helpers;

class Datatable {
    public static $request;
    public static $model;
    public static $records_total;
    public static $records_filtered;

    static function make ($request, $model) {
        self::$request = $request;
        self::$model = $model;
        self::setRecordsTotal();
        self::filter();
        self::setRecordsFiltered();
        self::orderLimit();
        self::renderJson();
    }

    // set total record count
    static function setRecordsTotal () {
        self::$records_total = self::$model->count();
    }

    // filter by search query
    static function filter () {
        if (!empty(self::$request['search']['value'])) {
            foreach (self::$request['columns'] as $column) {
                if ($column['searchable'] == 'true') {
                    self::$model->where($column['data'], 'LIKE', '%'.self::$request['search']['value'].'%');
                }
            }
        }
    }

    // set filtered record count
    static function setRecordsFiltered () {
        self::$records_filtered = self::$model->count();
    }

    // apply order by & limit
    static function orderLimit () {
        self::$model->orderBy(self::$request['columns'][self::$request['order'][0]['column']], self::$request['order'][0]['dir']);
        self::$model->skip(self::$request['start'])->take(self::$request['length']);
    }

    // render json output
    static function renderJson () {
        $array = [];
        $array['draw'] = self::$request['draw'];
        $array['recordsTotal'] = self::$records_total;
        $array['recordsFiltered'] = self::$records_filtered;
        $array['data'] = [];
        $results = self::$model->get();

        foreach ($results as $result) {
            $array['data'][] = $result->toArray();
        }

        echo json_encode($array);
    }
}

以下是我如何称呼课程:

Datatable::make($_POST, new User());

所以User在这个例子中是一个雄辩的模型。

现在,数据表的初始渲染效果很好。但是,当我尝试搜索或订购时,似乎我的filter()orderLimit()方法中的代码未应用,因为它只是按照完全相同的顺序吐出完全相同的结果

为什么我的where()orderBy()等未正确应用于模型?

1 个答案:

答案 0 :(得分:0)

想出来。我只需在我的::query()方法中使用make()模型,例如:

self::$model = $model::query()