改进BelongsTo关联

This commit is contained in:
thinkphp
2017-03-28 11:56:01 +08:00
parent 8d843bec99
commit 62aa6a0f14
4 changed files with 39 additions and 3 deletions

View File

@@ -1651,7 +1651,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
$model = $this->parseModel($model);
$foreignKey = $foreignKey ?: $this->getForeignKey($model);
$localKey = $localKey ?: (new $model)->getPk();
return new BelongsTo($this, $model, $foreignKey, $localKey, $joinType);
$trace = debug_backtrace(false, 2);
$relation = Loader::parseName($trace[1]['function']);
return new BelongsTo($this, $model, $foreignKey, $localKey, $joinType, $relation);
}
/**

View File

@@ -25,7 +25,7 @@ class BelongsTo extends OneToOne
* @param string $localKey 关联主键
* @param string $joinType JOIN类型
*/
public function __construct(Model $parent, $model, $foreignKey, $localKey, $joinType = 'INNER')
public function __construct(Model $parent, $model, $foreignKey, $localKey, $joinType = 'INNER', $relation = null)
{
$this->parent = $parent;
$this->model = $model;
@@ -33,6 +33,7 @@ class BelongsTo extends OneToOne
$this->localKey = $localKey;
$this->joinType = $joinType;
$this->query = (new $model)->db();
$this->relation = $realtion;
}
/**
@@ -168,4 +169,35 @@ class BelongsTo extends OneToOne
$result->setAttr(Loader::parseName($relation), $relationModel);
}
/**
* 添加关联数据
* @access public
* @param Model $model 关联模型对象
* @return Model
*/
public function associate($model)
{
$foreignKey = $this->foreignKey;
$pk = $model->getPk();
$this->parent->setAttr($foreignKey, $model->$pk);
$this->parent->save();
return $this->parent->setAttr($this->relation, $model);
}
/**
* 注销关联数据
* @access public
* @return Model
*/
public function dissociate()
{
$foreignKey = $this->foreignKey;
$this->parent->setAttr($foreignKey, null);
$this->parent->save();
return $this->parent->setAttr($this->relation, null);
}
}

View File

@@ -34,7 +34,7 @@ class MorphTo extends Relation
* @param array $alias 多态别名定义
* @param string $relation 关联名
*/
public function __construct(Model $parent, $morphType, $morphKey, $alias = [], $relation)
public function __construct(Model $parent, $morphType, $morphKey, $alias = [], $relation = null)
{
$this->parent = $parent;
$this->morphType = $morphType;

View File

@@ -30,6 +30,8 @@ abstract class OneToOne extends Relation
protected $joinType;
// 要绑定的属性
protected $bindAttr = [];
// 关联方法名
protected $relation;
/**
* 设置join类型