数据表时间字段使用的时间搓保存,使用查询过滤时发现时间区间查询没有关于时间搓查询的能力,只能是自己实现一个
表格查询过滤的between类型,默认是使用控件输入原值作为查询参数
Encore\Admin\Grid\Filter\Between
类文件的condition
方法源码
/**
* Get condition of this filter.
*
* @param array $inputs
*
* @return mixed
*/
public function condition($inputs)
{
if ($this->ignore) {
return;
}
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;
}
// 以下几行代码可以看出,`$value`输入数据是未经过处理的
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';
return $this->buildCondition($this->column, $this->value);
}
只要将输入数据处理为自己想要的格式就可以实现时间搓区间查询
在app/Admin/Extensions/Grid
目录下新建FilterBetween
类,继承Encore\Admin\Grid\Filter\Between
并重写condition方法
<?php
namespace App\Admin\Extensions\Grid;
use Illuminate\Support\Arr;
use Encore\Admin\Grid\Filter\Between;
/**
* 查询区间过滤
*/
class FilterBetween extends Between
{
// 数据处理回调
protected $valueMapCallback = null;
// 设置数据处理回调
public function valueMap( callable $c ) {
$this->valueMapCallback = $c;
return $this;
}
// 时间搓数据 将数据转为时间搓
public function timestampValue() {
$this->valueMapCallback = function($v) {
return \strtotime( $v );
};
return $this;
}
/**
* Get condition of this filter.
*
* @param array $inputs
*
* @return mixed
*/
public function condition($inputs)
{
if ($this->ignore) {
return;
}
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;
}
// begin 新增的代码, 有数据处理回调时将数据处理一遍
if( $this->valueMapCallback ) {
$value = \array_map( $this->valueMapCallback, $value );
}
// end
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';
return $this->buildCondition($this->column, $value);
}
}
在app/Admin/bootstrap.php
中,将表格查询过滤的between类型的实现类替换为新建的FilterBetween
类
// 文件头部添加
use Encore\Admin\Grid\Filter;
use App\Admin\Extensions\Grid\FilterBetween;
// ...
// 替换
Filter::extend( 'between', FilterBetween::class);
新between类型的使用
添加时间区间过滤时开启数据处理回调就可以了
$grid->filter(function( $filter )use($types) {
// ...
// 调用 timestampValue 函数开启数据转时间搓回调
$filter->between('start_time', __("Start time"))->datetime()->timestampValue();
// ...
});
标签:laravel,inputs,return,admin,value,查询,filter,column,function
From: https://www.cnblogs.com/whymust/p/16734399.html