Skip to content

Commit

Permalink
MorphOne关联支持绑定关联模型属性
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Apr 19, 2021
1 parent 3457576 commit 1119d97
Showing 1 changed file with 69 additions and 2 deletions.
71 changes: 69 additions & 2 deletions src/model/relation/MorphOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ class MorphOne extends Relation
*/
protected $type;

/**
* 绑定的关联属性
* @var array
*/
protected $bindAttr = [];

/**
* 构造函数
* @access public
Expand Down Expand Up @@ -78,6 +84,11 @@ public function getRelation(array $subRelation = [], Closure $closure = null)
$relationModel = $this->query->relation($subRelation)->find();

if ($relationModel) {
if (!empty($this->bindAttr)) {
// 绑定关联属性
$this->bindAttr($this->parent, $relationModel);
}

$relationModel->setParent(clone $this->parent);
}

Expand Down Expand Up @@ -154,7 +165,13 @@ public function eagerlyResultSet(array &$resultSet, string $relation, array $sub
$relationModel->exists(true);
}

$result->setRelation($relation, $relationModel);
if (!empty($this->bindAttr)) {
// 绑定关联属性
$this->bindAttr($result, $relationModel);
} else {
// 设置关联属性
$result->setRelation($relation, $relationModel);
}
}
}
}
Expand Down Expand Up @@ -188,7 +205,13 @@ public function eagerlyResult(Model $result, string $relation, array $subRelatio
$relationModel = null;
}

$result->setRelation($relation, $relationModel);
if (!empty($this->bindAttr)) {
// 绑定关联属性
$this->bindAttr($result, $relationModel);
} else {
// 设置关联属性
$result->setRelation($relation, $relationModel);
}
}
}

Expand Down Expand Up @@ -277,4 +300,48 @@ protected function baseQuery(): void
}
}

/**
* 绑定关联表的属性到父模型属性
* @access public
* @param array $attr 要绑定的属性列表
* @return $this
*/
public function bind(array $attr)
{
$this->bindAttr = $attr;

return $this;
}

/**
* 获取绑定属性
* @access public
* @return array
*/
public function getBindAttr(): array
{
return $this->bindAttr;
}

/**
* 绑定关联属性到父模型
* @access protected
* @param Model $result 父模型对象
* @param Model $model 关联模型对象
* @return void
* @throws Exception
*/
protected function bindAttr(Model $result, Model $model = null): void
{
foreach ($this->bindAttr as $key => $attr) {
$key = is_numeric($key) ? $attr : $key;
$value = $result->getOrigin($key);

if (!is_null($value)) {
throw new Exception('bind attr has exists:' . $key);
}

$result->setAttr($key, $model ? $model->$attr : null);
}
}
}

0 comments on commit 1119d97

Please sign in to comment.