Laravel 多级联动

Laravel 多级联动

中国行政区多级联动

数据来源:GitHub

数据库结构

1
2
3
4
5
create table `district` (
`id` int not null primary key unique,
`name` varchar(255) not null,
`pid` int null
) CHARSET=utf8;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
protected $data;

protected $keys;

protected $result;

protected $typeList = [
'pc', //省份、城市
'pca', //省份、城市、区县
'pcas' //省份、城市、区县、乡镇
];

protected function update($type = 1)
{
$url = 'https://raw.githubusercontent.com/modood/Administrative-divisions-of-China/master/dist/' . $this->typeList[$type] . '-code.json';

$data = json_decode(file_get_contents($url), true);

$this->result = DB::table('district')->get();

$this->keys = $this->result->pluck('id')->toArray();

$this->getItem($data);

DB::table('district')->whereIn('id', $this->keys)
->delete();

return true;
}

protected function getItem($data, $pid = 0)
{
foreach($data as $value) {
if(isset($value['children'])) {
$this->getItem($value['children'], $value['code']);
}

$item = $this->result->firstWhere('id', $value['code']);

if($item) {
array_splice($this->keys, array_search($value['code'], $this->keys), 1);

if($item->name !== $value['name'] || $item->pid !== $pid) {
DB::table('district')->where('id', $value['code'])
->update([
'name' => $value['name'],
'pid' => $pid
]);
}
} else {
DB::table('district')->insert([
'id' => $value['code'],
'name' => $value['name'],
'pid' => $pid
]);
}
}
}

public function index()
{
$result = DB::table('district')->select('id', 'name')
->where('pid' , request('pid', 0))
->get()
->toArray();

return response()->json($result);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<div class="container">
<select name="province">
<option value="0">请选择</option>
</select>

<select name="city">
<option value="0">请选择</option>
</select>

<select name="area">
<option value="0">请选择</option>
</select>
</div>

<script>
$(function() {
getData('province', 0);

$('.container select').on('change', function() {
const self = $(this);

if($('select:last-of-type').attr('name') !== self.attr('name')) {
getData(self.next().attr('name'), self.val());
}
});
});

function getData(name, pid) {
const select = $('select[name="' + name + '"]');

$.get('/district/' + pid, response => {
if(!response.length) return false;

const html = response.map(item => {
return '<option value="' + item.id + '">' + item.name + '</option>';
});

$('select[name="' + name + '"]').html(html.join(''));

if($('select:last-of-type').attr('name') !== name) {
getData(select.next().attr('name'), response[0].id);
}
});
}
</script>
往上