Dcat-admin 2.x 多级联动
需求
一个省市区的三级联动功能 在表单中,需要可以实现三级联动 在列表的查询中,也需要实现三级联动
实现说明
前提:dcat-admin 提供了 一个 load 方法,有两个参数,第一个是选项框的字段名,第二个是接口路由,可以用它来实现联动 我们实现一个接口,接口一个ID,可以返回下级的省市区。给省的Id,就返回该省下的所有市 页面选项框选择后,会拿到选择的值,并去调用 load 方法指定接口 拿到接口返回值,去设置到 load 方法指定的字段上,用于充当选项
示例代码
$provinces = RegionPlus :: query ( ) -> where ( 'pid' , 1 ) -> pluck ( 'name' , 'id' ) ;
$form -> select ( 'merchant_province_id' ) -> default ( 0 ) -> value ( 0 ) -> options ( $provinces ) -> load ( 'merchant_city_id' , '/api/region' ) -> required ( ) -> help ( '详细地址省ID必填此项' ) ;
$form -> select ( 'merchant_city_id' )
-> default ( 0 )
-> value ( 0 )
-> load ( 'merchant_area_id' , '/api/region' )
-> required ( )
-> help ( '详细地址市ID必填此项' ) ;
$form -> select ( 'merchant_area_id' ) -> default ( 0 ) -> value ( 0 ) -> required ( ) -> help ( '详细地址区ID必填此项' ) ;
$provinces = RegionPlus :: query ( ) -> where ( 'pid' , 1 ) -> pluck ( 'name' , 'id' ) ;
$filter -> equal ( 'merchant_province_id' , '省' ) -> select ( $provinces ) -> load ( 'merchant_city_id' , '/api/region' ) -> ignore ( ) ;
$filter -> equal ( 'merchant_city_id' , '市' ) -> select ( ) -> load ( 'merchant_area_id' , '/api/region' ) -> ignore ( ) ;
$filter -> equal ( 'merchant_area_id' , '区' ) -> select ( ) ;
$router -> get ( 'api/region' , 'Api\RegionPlusController@region' ) ;
public function region ( Request $request )
{
$parentId = $request -> get ( 'q' ) ;
$response = RegionPlus :: query ( ) -> where ( 'pid' , $parentId ) -> get ( [
'id' ,
DB :: raw ( 'name as text' )
] ) ;
return $this -> json ( $response ) -> notError ( ) ;
}
数据表结构
CREATE TABLE ` region_pluses` (
` id` int ( 10 ) unsigned NOT NULL DEFAULT '0' ,
` name` varchar ( 50 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '名称' ,
` abbr` varchar ( 50 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '缩写' ,
` pinyin` varchar ( 100 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '拼音' ,
` t_name` varchar ( 50 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '繁体' ,
` pid` int ( 10 ) unsigned NOT NULL DEFAULT '0' COMMENT 'pid' ,
` type` tinyint ( 3 ) unsigned NOT NULL DEFAULT '0' COMMENT '类型' ,
` zip` varchar ( 10 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '邮编' ,
` enabled` tinyint ( 3 ) unsigned NOT NULL DEFAULT '0' COMMENT '是否启用' ,
` created_at` timestamp NULL DEFAULT NULL ,
` updated_at` timestamp NULL DEFAULT NULL ,
` first_letter` char ( 1 ) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '首字母' ,
` merge_id` int ( 10 ) unsigned NOT NULL DEFAULT '0' COMMENT '合并ID,即被归属的行政区域ID' ,
UNIQUE KEY ` region_pluses_id_unique` ( ` id` ) USING BTREE ,
KEY ` region_pluses_name_index` ( ` name` ) USING BTREE
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;