改进多态关联

This commit is contained in:
thinkphp
2017-03-28 11:40:50 +08:00
parent 82e8da05e2
commit 8d843bec99
2 changed files with 14 additions and 8 deletions

View File

@@ -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)

View File

@@ -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);
}
/**