laravel-admin 的 between()->datetime();

laravel 版本 6.5.2

laravel-admin 版本 1.5

 

下面是laravel-admin 的一個篩選組件datetime,第一個選項可以格式化組件樣式,比如只篩選年,或者月啥的,第二個參數是我自己加的

$grid->filter(function ($filter) {
    $filter->disableIdFilter();
    $filter->between('create_time', 'Created Time')->datetime([],true);
});

會生成一個這樣的篩選框,我用這個來篩選數據的創建時間,字段:create_time

但是會有一個問題,create_time字段是時間戳格式的,而這個篩選,是字符串

跟蹤源碼,找到了這個datetime方法,在 vendor/encore/laravel-admin/src/Grid/Filter/Between.php,下面是解決方法

1,在Between類中加入$timestamp屬性

2,在Between類中的 condition 方法里加上判斷

public function condition($inputs)
{
    if (!Arr::has($inputs, $this->column)) {
        return;
    }

    $this->value = Arr::get($inputs, $this->column);

    $value = array_filter($this->value, function ($val) {
        return $val !== '';
    });

    if (empty($value)) {
        return;
    }

    if (!isset($value['start'])) {
        return $this->buildCondition($this->column, '<=', $value['end']);
    }

    if (!isset($value['end'])) {
        return $this->buildCondition($this->column, '>=', $value['start']);
    }

    $this->query = 'whereBetween';
        
    //下面這4行
    if($this->timestamp){
        $this->value['start'] = strtotime($this->value['start']);
        $this->value['end'] = strtotime($this->value['end']);
    }

    return $this->buildCondition($this->column, $this->value);
}

3,在 datetime 方法中設置 timestamp 的值

public function datetime($options = [],$timestamp = false)
{
    $this->view = 'admin::filter.betweenDatetime';

    $this->setupDatetime($options);

    $this->timestamp = $timestamp;

    return $this;
}

4,回到開頭,在調用datetime方法的時候,第二個參數傳true就可以了

============================================================================================

調用順序

$grid->filter方法 >> HasFilter類 >> filter方法 >> Filter類 >> __call方法 >> Between類 >> date
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章