diff --git a/src/model/concern/Attribute.php b/src/model/concern/Attribute.php index 9cd0abbc..fbd93734 100644 --- a/src/model/concern/Attribute.php +++ b/src/model/concern/Attribute.php @@ -15,7 +15,6 @@ use BackedEnum; use Closure; -use InvalidArgumentException; use Stringable; use think\db\Express; use think\db\Raw; diff --git a/src/model/concern/Conversion.php b/src/model/concern/Conversion.php index 4b8fe0ee..4d5fa4f0 100644 --- a/src/model/concern/Conversion.php +++ b/src/model/concern/Conversion.php @@ -108,8 +108,8 @@ public function toArray(): array if ($val instanceof Modelable || $val instanceof Collection) { if (!empty($relation[$name])) { // 处理关联数据输出 - foreach ($relation[$name] as $key => $val) { - $val->$key($val); + foreach ($relation[$name] as $key => $attr) { + $val->$key($attr); } } $item[$name] = $val->toarray(); @@ -126,8 +126,16 @@ public function toArray(): array } // 输出额外属性 必须定义获取器 - foreach ($this->getOption('append') as $key) { - $item[$key] = $this->get($key); + foreach ($this->getOption('append') as $key => $field) { + if (is_numeric($key)) { + $item[$field] = $this->get($field); + } else { + // 追加关联属性 + $relation = $this->getRelationData($key, false); + foreach((array) $field as $name) { + $item[$name] = $relation[$name]; + } + } } return $item; diff --git a/src/model/concern/RelationShip.php b/src/model/concern/RelationShip.php index bc1acd1f..c9f324d4 100644 --- a/src/model/concern/RelationShip.php +++ b/src/model/concern/RelationShip.php @@ -160,17 +160,20 @@ private function relationDelete(array $relations = []) * 获取关联数据 * * @param string $name 名称 + * @param bool $set 是否设置为当前模型属性 * * @return mixed */ - protected function getRelationData(string $name) + protected function getRelationData(string $name, bool $set = true) { $method = Str::camel($name); if (method_exists($this, $method)) { $modelRelation = $this->$method(); if ($modelRelation instanceof Relation) { $value = $modelRelation->getRelation(); - $this->setData($name, $value); + if ($set) { + $this->setData($name, $value); + } return $value; } }