Skip to content

Commit 8558e1e

Browse files
committed
fix: 对于嵌套的模型列表,会丢失数组的key
1 parent 60f3bef commit 8558e1e

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ $data = [
152152
"name" => "Alice",
153153
"age" => 8,
154154
],
155-
[
155+
's' => [
156156
"name" => "Bob",
157157
"age" => 10,
158158
]
@@ -199,6 +199,7 @@ $info = new Info($data);
199199

200200
assert(count($info->studentList) === 2);
201201
assert($info->studentList[0]->name === 'Alice');
202+
assert($info->studentList['s']->name === 'Bob');
202203
assert($info->school->name === 'xxx');
203204
```
204205

src/Converters/ModelListConverter.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,12 @@ public function convert(mixed $fieldValue, Property $property): array
2626
}
2727

2828
$result = [];
29-
foreach ($fieldValue as $each) {
29+
foreach ($fieldValue as $key => $each) {
3030
if (!is_array($each)) {
3131
throw new TypeError("the element of {$property->getBoundFieldName()} should be a type of array");
3232
}
3333

34-
$result[] = new $this->modelClass($each);
34+
$result[$key] = new $this->modelClass($each);
3535
}
3636

3737
return $result;

tests/ModelConverterTest.php

+28-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public function testRecursiveDataModel()
2626
['field' => 3],
2727
['field' => 4],
2828
],
29-
]
29+
],
3030
],
3131
]);
3232

@@ -40,6 +40,33 @@ public function testRecursiveDataModel()
4040
$this->assertEquals(3, $model->outerList[1]->innerList[0]->val);
4141
$this->assertEquals(4, $model->outerList[1]->innerList[1]->val);
4242

43+
44+
$model = new EmbedDataListModel([
45+
'outers' => [
46+
'outer1' => [
47+
'inners' => [
48+
'inner1_a' => ['field' => 1],
49+
'inner1_b' => ['field' => 2],
50+
],
51+
],
52+
'outer2' => [
53+
'inners' => [
54+
'inner2_a' => ['field' => 3],
55+
'inner2_b' => ['field' => 4],
56+
],
57+
],
58+
],
59+
]);
60+
$this->assertCount(2, $model->outerList);
61+
62+
$this->assertCount(2, $model->outerList['outer1']->innerList);
63+
$this->assertEquals(1, $model->outerList['outer1']->innerList['inner1_a']->val);
64+
$this->assertEquals(2, $model->outerList['outer1']->innerList['inner1_b']->val);
65+
66+
$this->assertCount(2, $model->outerList['outer2']->innerList);
67+
$this->assertEquals(3, $model->outerList['outer2']->innerList['inner2_a']->val);
68+
$this->assertEquals(4, $model->outerList['outer2']->innerList['inner2_b']->val);
69+
4370
}
4471

4572
public function testInvalidFieldType_ExpectError()

0 commit comments

Comments
 (0)