diff --git a/library/think/Model.php b/library/think/Model.php index 47fdc502..40b8dfe1 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -1747,9 +1747,11 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function morphTo($morph = null, $alias = []) { + $trace = debug_backtrace(false, 2); + $relation = Loader::parseName($trace[1]['function']); + if (is_null($morph)) { - $trace = debug_backtrace(false, 2); - $morph = Loader::parseName($trace[1]['function']); + $morph = $relation; } // 记录当前关联信息 if (is_array($morph)) { @@ -1758,7 +1760,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $morphType = $morph . '_type'; $foreignKey = $morph . '_id'; } - return new MorphTo($this, $morphType, $foreignKey, $alias); + return new MorphTo($this, $morphType, $foreignKey, $alias, $relation); } public function __call($method, $args) diff --git a/library/think/model/relation/MorphTo.php b/library/think/model/relation/MorphTo.php index d406e8f8..c660a757 100644 --- a/library/think/model/relation/MorphTo.php +++ b/library/think/model/relation/MorphTo.php @@ -23,6 +23,7 @@ class MorphTo extends Relation protected $morphType; // 多态别名 protected $alias; + protected $relation; /** * 构造函数 @@ -31,13 +32,15 @@ class MorphTo extends Relation * @param string $morphType 多态字段名 * @param string $morphKey 外键名 * @param array $alias 多态别名定义 + * @param string $relation 关联名 */ - public function __construct(Model $parent, $morphType, $morphKey, $alias = []) + public function __construct(Model $parent, $morphType, $morphKey, $alias = [], $relation) { $this->parent = $parent; $this->morphType = $morphType; $this->morphKey = $morphKey; $this->alias = $alias; + $this->relation = $relation; } /** @@ -237,13 +240,13 @@ class MorphTo extends Relation $this->parent->setAttr($morphKey, $model->$pk); $this->parent->setAttr($morphType, get_class($model)); $this->parent->save(); - return $this; + + return $this->parent->setAttr($this->relation, $model); } /** - * 添加关联数据 + * 注销关联数据 * @access public - * @param Model $model 关联模型对象 * @return Model */ public function dissociate() @@ -254,7 +257,8 @@ class MorphTo extends Relation $this->parent->setAttr($morphKey, null); $this->parent->setAttr($morphType, null); $this->parent->save(); - return $this; + + return $this->parent->setAttr($this->relation, null); } /**