From 099c977b0a035d765789cb56fe73c373d07f1d59 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Wed, 30 Nov 2016 22:52:42 +0800 Subject: [PATCH] =?UTF-8?q?morphTo=E6=94=AF=E6=8C=81=E5=A4=9A=E6=80=81?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E5=AD=97=E6=AE=B5=E5=88=AB=E5=90=8D=E5=AE=9A?= =?UTF-8?q?=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 7 ++++--- library/think/model/Relation.php | 18 +++++++++++++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/library/think/Model.php b/library/think/Model.php index 32ce4e52..c626ea31 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1388,10 +1388,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess /** * MORPH TO 关联定义 * @access public - * @param string|array $morph 多态字段信息 + * @param string|array $morph 多态字段信息 + * @param array $alias 多态别名定义 * @return Relation */ - public function morphTo($morph) + public function morphTo($morph, $alias = []) { // 记录当前关联信息 if (is_array($morph)) { @@ -1400,7 +1401,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $morphType = $morph . '_type'; $foreignKey = $morph . '_id'; } - return $this->relation()->morphTo($morphType, $foreignKey); + return $this->relation()->morphTo($morphType, $foreignKey, $alias); } public function __call($method, $args) diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php index dbef09d3..c206c91d 100644 --- a/library/think/model/Relation.php +++ b/library/think/model/Relation.php @@ -129,10 +129,16 @@ class Relation case self::MORPH_TO: // 多态模型 $model = $this->parent->{$this->middle}; - $path = explode('\\', get_class($this->parent)); - array_pop($path); - array_push($path, Loader::parseName($model, 1)); - $model = implode('\\', $path); + // 多态类型映射 + if (isset($this->alias[$model])) { + $model = $this->alias[$model]; + } + if (false === strpos($model, '\\')) { + $path = explode('\\', get_class($this->parent)); + array_pop($path); + array_push($path, Loader::parseName($model, 1)); + $model = implode('\\', $path); + } // 主键数据 $pk = $this->parent->{$this->foreignKey}; $result = (new $model)->find($pk); @@ -559,14 +565,16 @@ class Relation * @access public * @param string $morphType 多态字段名 * @param string $foreignKey 外键名 + * @param array $alias 多态别名定义 * @return $this */ - public function morphTo($morphType, $foreignKey) + public function morphTo($morphType, $foreignKey, $alias) { // 记录当前关联信息 $this->type = self::MORPH_TO; $this->middle = $morphType; $this->foreignKey = $foreignKey; + $this->alias = $alias; // 返回关联的模型对象 return $this; }