laravel-admin中实现三级联动筛选搜索功能流程步骤
2023-06-01 00:00:00
laravel
网上大部分写的比较模糊,刚好我的项目需要做这个功能,我这就根据我的项目实现省市区三级列表筛选搜索功能,记录一下
开始环境啥的就不说了,就是laravel-admin
1.表结构
CREATE TABLE `city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` char(30) DEFAULT NULL,
`pid` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`) USING BTREE,
KEY `pid` (`pid`) USING BTREE,
KEY `t` (`title`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3896 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
2.模型
<?php
namespace App\Models;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Model;
class Wdcity extends Model
{
protected $table = 'city';
public static function grid($callback)
{
return new Grid(new static, $callback);
}
public static function form($callback)
{
return new Form(new static, $callback);
}
public function parent()
{
return $this->belongsTo(Wdcity::class, 'pid');
}
public function children()
{
return $this->hasMany(Wdcity::class, 'pid');
}
public function brothers()
{
return $this->parent->children();
}
public static function options($id)
{
if (! $self = static::find($id)) {
return [];
}
return $self->brothers()->pluck('title', 'id');
}
}
3.控制器中 联动接口调用
<?php
namespace App\Admin\Controllers;
use App\Models\Wdcity;
use App\Models\SelectOption;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class WdcityController extends Controller
{
use HasResourceActions;
private $title = '城市管理';
private $states = [
'on' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
'off' => ['value' => 1, 'text' => '是', 'color' => 'success'],
];
public function city(Request $request)
{
$pid = $request->get('q');
return Wdcity::where('pid', $pid)->get(['id', DB::raw('title as text')]);
}
public function district(Request $request)
{
$cityId = $request->get('q');
return Wdcity::where('pid', $cityId)->get(['id', DB::raw('title as text')]);
}
}
4.路由
$router->get('api/wdcity/city', '[email protected]');
$router->get('api/wdcity/district', '[email protected]');
5.筛选中调用 实现省市区三级联动
/**
* Make a grid builder.
*
* @return Grid
*/
protected function grid()
{
$grid = new Grid(new Bankwd());
$grid->id('ID')->sortable();
$grid->filter(function($filter){
// 去掉默认的id过滤器
//$filter->disableIdFilter();
$filter->like('bankname','名称');
$filter->equal('bankid','银行')->select(SelectOption::wdbanktypelist());
//这里就是三级联动调用
$filter->equal('citys1', '省份')->select(Wdcity::where('pid',0)->orderBy('title')->pluck('title', 'id'))
->load('citys2', '/api/wdcity/city');
$filter->equal('citys2', '城市')->select(Wdcity::where('pid','<>',0)->orderBy('title')->pluck('title', 'id'))
->load('city3', '/api/wdcity/district');
$filter->equal('city3', '区')->select(function ($id) {
return Wdcity::options($id);
});
});
return $grid;
}
6.废话不多说 直接看效果
完
相关文章