From cfb7b321fd08d0e691da88eeb1a37a20f91056e8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 19 Nov 2024 14:28:51 +0800 Subject: [PATCH] =?UTF-8?q?hidden/visible/append=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=85=B3=E8=81=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Entity.php | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/Entity.php b/src/Entity.php index e0b4b758..919cac8c 100644 --- a/src/Entity.php +++ b/src/Entity.php @@ -693,16 +693,33 @@ public function toArray(array $allow = []): array { $data = $this->getData(); if (empty($allow)) { - $hidden = self::$weakMap[$this]['hidden']; - $visible = self::$weakMap[$this]['visible']; - $allow = array_diff($visible ?: array_keys($data), $hidden); + foreach (['visible', 'hidden', 'append'] as $convert) { + ${$convert} = self::$weakMap[$this][$convert]; + foreach (${$convert} as $key => $val) { + if (is_string($key)) { + $relation[$key][$convert] = $val; + unset(${$convert}[$key]); + } elseif (str_contains($val, '.')) { + [$relName, $name] = explode('.', $val); + $relation[$relName][$convert][] = $name; + unset(${$convert}[$key]); + } + } + } + $allow = array_diff($visible ?: array_keys($data), $hidden); } - + foreach ($data as $name => &$item) { - if (!empty($allow) && !in_array($name, $allow)) { - unset($data[$name]); - } elseif ($item instanceof Entity || $item instanceof Collection) { + if ($item instanceof Entity || $item instanceof Collection) { + if (!empty($relation[$name])) { + // 处理关联数据输出 + foreach ($relation[$name] as $key => $val) { + $item->$key($val); + } + } $item = $item->toarray(); + } elseif (!empty($allow) && !in_array($name, $allow)) { + unset($data[$name]); } elseif ($item instanceof Typeable) { $item = $item->value(); } elseif (is_subclass_of($item, EnumTransform::class)) { @@ -726,7 +743,7 @@ public function toArray(array $allow = []): array } } - // 输出额外属性 + // 输出额外属性 必须定义获取器 foreach (self::$weakMap[$this]['append'] as $key) { $data[$key] = $this->get($key); }