Skip to content

Commit

Permalink
完善关联的save方法
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Dec 6, 2018
1 parent 964f4c6 commit 7be580f
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
16 changes: 14 additions & 2 deletions library/think/model/relation/HasMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -201,14 +201,26 @@ protected function eagerlyOneToMany($model, $where, $relation, $subRelation = ''
* @return Model|false
*/
public function save($data)
{
$model = $this->make($data);
return $model->save($data) ? $model : false;
}

/**
* 创建关联对象实例
* @param array $data
* @return Model
*/
public function make($data = [])
{
if ($data instanceof Model) {
$data = $data->getData();
}

// 保存关联表数据
$model = new $this->model;
$data[$this->foreignKey] = $this->parent->{$this->localKey};
return $model->save($data) ? $model : false;

return new $this->model($data);
}

/**
Expand Down
17 changes: 15 additions & 2 deletions library/think/model/relation/MorphMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,17 +244,30 @@ protected function eagerlyMorphToMany($where, $relation, $subRelation = '', $clo
* @return Model|false
*/
public function save($data)
{
$model = $this->make($data);

return $model->save($data) ? $model : false;
}

/**
* 创建关联对象实例
* @param array $data
* @return Model
*/
public function make($data = [])
{
if ($data instanceof Model) {
$data = $data->getData();
}

// 保存关联表数据
$pk = $this->parent->getPk();

$model = new $this->model;
$data[$this->morphKey] = $this->parent->$pk;
$data[$this->morphType] = $this->type;
return $model->save($data) ? $model : false;

return new $this->model($data);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions library/think/model/relation/MorphOne.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function __construct(Model $parent, $model, $morphKey, $morphType, $type)
public function getRelation($subRelation = '', $closure = null)
{
if ($closure) {
call_user_func_array($closure, [& $this->query]);
call_user_func_array($closure, [ & $this->query]);
}
$relationModel = $this->relation($subRelation)->find();

Expand Down Expand Up @@ -179,7 +179,7 @@ protected function eagerlyMorphToOne($where, $relation, $subRelation = '', $clos
{
// 预载入关联查询 支持嵌套预载入
if ($closure) {
call_user_func_array($closure, [& $this]);
call_user_func_array($closure, [ & $this]);
}
$list = $this->query->where($where)->with($subRelation)->find();
$morphKey = $this->morphKey;
Expand All @@ -206,7 +206,7 @@ public function save($data)
/**
* 创建关联对象实例
* @param array $data
* @return mixed
* @return Model
*/
public function make($data = [])
{
Expand Down

0 comments on commit 7be580f

Please sign in to comment.