|
2 | 2 |
|
3 | 3 | namespace Tempest\Database\Mappers; |
4 | 4 |
|
| 5 | +use Tempest\Database\BelongsTo; |
5 | 6 | use Tempest\Database\Builder\ModelInspector; |
| 7 | +use Tempest\Database\HasMany; |
| 8 | +use Tempest\Database\HasOne; |
6 | 9 | use Tempest\Discovery\SkipDiscovery; |
7 | 10 | use Tempest\Mapper\Mapper; |
8 | 11 |
|
@@ -43,39 +46,39 @@ private function normalizeFields(ModelInspector $model, array $rows): array |
43 | 46 |
|
44 | 47 | foreach ($rows as $row) { |
45 | 48 | foreach ($row as $field => $value) { |
46 | | - $mainField = explode('.', $field)[0]; |
| 49 | + $parts = explode('.', $field); |
| 50 | + |
| 51 | + $mainField = $parts[0]; |
47 | 52 |
|
48 | 53 | // Main fields |
49 | 54 | if ($mainField === $mainTable) { |
50 | | - $data[substr($field, strlen($mainTable) + 1)] = $value; |
| 55 | + $data[$parts[1]] = $value; |
51 | 56 | continue; |
52 | 57 | } |
53 | 58 |
|
54 | | - // BelongsTo |
55 | | - if ($belongsTo = $model->getBelongsTo($mainField)) { |
56 | | - $data[$belongsTo->property->getName()][str_replace($mainField . '.', '', $field)] = $value; |
57 | | - continue; |
58 | | - } |
| 59 | + $relation = $model->getRelation($parts[0]); |
| 60 | + |
| 61 | + // IF count > 2 |
59 | 62 |
|
60 | | - // HasOne |
61 | | - if ($hasOne = $model->getHasOne($mainField)) { |
62 | | - $data[$hasOne->property->getName()][str_replace($mainField . '.', '', $field)] = $value; |
| 63 | + // BelongsTo |
| 64 | + if ($relation instanceof BelongsTo || $relation instanceof HasOne) { |
| 65 | + $data[$relation->name][$parts[1]] = $value; |
63 | 66 | continue; |
64 | 67 | } |
65 | 68 |
|
66 | 69 | // HasMany |
67 | | - if ($hasMany = $model->getHasMany($mainField)) { |
68 | | - $hasManyId = $row[$hasMany->idField()]; |
| 70 | + if ($relation instanceof HasMany) { |
| 71 | + $hasManyId = $row[$relation->idField()]; |
69 | 72 |
|
70 | 73 | if ($hasManyId === null) { |
71 | 74 | // Empty has many relations are initialized it with an empty array |
72 | | - $data[$hasMany->property->getName()] ??= []; |
| 75 | + $data[$relation->name] ??= []; |
73 | 76 | continue; |
74 | 77 | } |
75 | 78 |
|
76 | | - $hasManyRelations[$hasMany->property->getName()] ??= $hasMany; |
| 79 | + $hasManyRelations[$relation->name] ??= $relation; |
77 | 80 |
|
78 | | - $data[$hasMany->property->getName()][$hasManyId][str_replace($mainField . '.', '', $field)] = $value; |
| 81 | + $data[$relation->name][$hasManyId][str_replace($mainField . '.', '', $field)] = $value; |
79 | 82 | } |
80 | 83 | } |
81 | 84 | } |
|
0 commit comments