我需要知道如何从数据库表中创建数组。我想要这样的东西。我在数据库国家(州)-城市中有3个表
数据库结构如下
countries
-表:
| id | country |
|----|----------------|
| 1 | united kingdom |
states
-表
| id | state |
|----|----------------------|
| 1 | united westyorkshite |
cities
-表
| id | city |
|----|----------------------|
| 1 | united wakefield |
预期结果:
{
value: '12',
label: 'United Kingdom',
children: [
{
values: '34',
labels: 'West YorkShire',
children: [
{
value: '400',
label: 'Dewsbury'
},
{
value: '401',
label: 'Wakefield'
}
]
}
这是我尝试过的:
$country_array = array();
$array = Country::select('countries.country', 'countries.country_id')
->isDefault()
->active()
->sorted()
->pluck('countries.country', 'countries.country_id')
->toArray();
// print_r($array);
foreach($array as $key => $arr) {
$array_state = State::select('states.state', 'states.state_id')
->where('states.country_id', '=', $key)
->isDefault()
->active()
->sorted()
->pluck('states.state', 'states.state_id')
->toArray();
foreach($array_state as $key_1 => $arr_1) {
$array_city = City::select('cities.city', 'cities.city_id')
->where('cities.state_id', '=', $key_1)
->active()
->sorted()
->pluck('cities.city', 'cities.city_id')
->toArray();
$array_state_1 [] = array (
'value' => $key_1,
'label' => $arr_1,
'children' => $array_city
);
}
$country_array [] = array (
'value' => $key,
'label' => $arr,
'children' => $array_state
);
}
dd($country_array);
我需要这些标签以及值和标签。我无法删除它,因为我正在使用vuejs元素ui组件。
我尝试使用普通的foreach循环,但超时。知道我如何使用地图或集合在laravel中做到这一点,或者什么是最佳解决方案。
我正在使用php 7,而laravel版本是5.6
答案 0 :(得分:0)
要在单个语句中检索所有必要的数据,我将使用嵌套的。例如:
CONNECT localhost:4080 HTTP/1.1
Host: 127.0.0.1:9090
User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_191)
下一步是修改数据。尽管嵌套使它看起来有些复杂,但map()函数确实对于此目的非常有用:
HTTP/1.1 407 Proxy Authentication Required
Server: Proxy
Proxy-Authenticate: Basic realm="**** Authorization"
Cache-control: no-cache
Connection: Close
Proxy-Connection: Close
Content-Length: 0
最后要显示它,我们将整个内容转换为JSON数组。
$result = Country::where('country_id', 12)
->with(['states' => function ($query) {
$query->where('state_id', 34);
$query->with('cities');
}])
->get();
哪个给我:
$mapped = $result->map(function ($country, $key) {
return [
'value' => $country->country_id,
'label' => $country->country,
'children' => $country->states->map(function ($state, $key) {
return [
'value' => $state->state_id,
'label' => $state->state,
'children' => $state->cities->map(function ($city, $key) {
return [
'value' => $city->city_id,
'label' => $city->city,
];
}),
];
}),
];
});