Yii2中省市三级联动(栏目联动)

时间:2023-03-09 15:37:49
Yii2中省市三级联动(栏目联动)
先从表的设计开始:
表的结构: CREATE TABLE `global_region` (
`region_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`parent_id` smallint(5) unsigned NOT NULL DEFAULT '0',
`region_name` varchar(120) NOT NULL DEFAULT '',
`region_type` tinyint(1) NOT NULL DEFAULT '2',
PRIMARY KEY (`region_id`),
KEY `parent_id` (`parent_id`),
KEY `region_type` (`region_type`)
) ENGINE=MyISAM AUTO_INCREMENT=3409 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of global_region
-- ----------------------------
INSERT INTO `global_region` VALUES ('1', '0', '中国', '0');
INSERT INTO `global_region` VALUES ('2', '1', '北京', '1');
INSERT INTO `global_region` VALUES ('3', '1', '安徽', '1');
INSERT INTO `global_region` VALUES ('4', '1', '福建', '1');
INSERT INTO `global_region` VALUES ('5', '1', '甘肃', '1');
INSERT INTO `global_region` VALUES ('6', '1', '广东', '1');
INSERT INTO `global_region` VALUES ('7', '1', '广西', '1');
INSERT INTO `global_region` VALUES ('8', '1', '贵州', '1');
INSERT INTO `global_region` VALUES ('9', '1', '海南', '1');
INSERT INTO `global_region` VALUES ('10', '1', '河北', '1');
INSERT INTO `global_region` VALUES ('11', '1', '河南', '1');
INSERT INTO `global_region` VALUES ('12', '1', '黑龙江', '1'); 这里只贴出来数据库的一部分代码
这个是视图view层代码: <?=$form->field($model, 'provinces')->dropDownList(ArrayHelper::map(common\models\GlobalRegion::find()->where(['region_type'=>1])->asArray()->all(),'region_id','region_name'),
[
'style'=>'width:150px',
'prompt'=>'请选择省',
'onchange'=>'
$.post("index.php?r=user/lists&id='.'"+$(this).val(),function(data){
$("#user-citys").html("<option value=>请选择市</option>");
$("#user-countrys").html("<option value=>请选择县</option>");
$("#user-citys").append(data);
});',
])->label('省份'); ?> <?=$form->field($model, 'citys')->dropDownList(ArrayHelper::map(common\models\GlobalRegion::find()->where(['region_type'=>2])->asArray()->all(),'region_id','region_name'),
[
'style'=>'width:150px',
'prompt'=>'请选择市',
'onchange'=>' $.post("index.php?r=user/lists&id='.'"+$(this).val(),function(data){
$("#user-countrys").html("<option value=>请选择县</option>");
$("#user-countrys").append(data);
});',
])->label('市'); ?> <?=$form->field($model, 'countrys')->dropDownList(ArrayHelper::map(common\models\GlobalRegion::find()->where(['region_type'=>3])->asArray()->all(),'region_id','region_name'),
[
'style'=>'width:150px',
'prompt'=>'请选择县',
'onchange'=>'
$.post("index.php?r=branches/lists&amp;id='.'"+$(this).val(),function(data){ });',
])->label('区/县'); ?> 这里我没有用json,而是直接在后台把option拼出来了,不过我觉得可以试试json,不知道为什么,我用json时遍历时老是出错,回头我再试试

给个建议,用 DAO 而不是 AR 来查询更高效。而且用 DAO 查出来的直接就是数组了