Skip to content

Commit

Permalink
改进模型输出append方法支持追加关联属性
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Feb 28, 2025
1 parent e184dc3 commit 9baada0
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
1 change: 0 additions & 1 deletion src/model/concern/Attribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

use BackedEnum;
use Closure;
use InvalidArgumentException;
use Stringable;
use think\db\Express;
use think\db\Raw;
Expand Down
16 changes: 12 additions & 4 deletions src/model/concern/Conversion.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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;
Expand Down
7 changes: 5 additions & 2 deletions src/model/concern/RelationShip.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down

0 comments on commit 9baada0

Please # to comment.