改进多对多关联的中间表模型更新

This commit is contained in:
thinkphp
2018-05-11 14:02:47 +08:00
parent 151052cd3f
commit 7ab73d1058

View File

@@ -79,22 +79,23 @@ class BelongsToMany extends Relation
{ {
return [ return [
$this->localKey => $data[$this->localKey], $this->localKey => $data[$this->localKey],
$this->foreignKey => $data[$this->foreignKey] $this->foreignKey => $data[$this->foreignKey],
]; ];
} }
/** /**
* 实例化中间表模型 * 实例化中间表模型
* @param $data * @param array $data
* @param bool $isUpdate
* @return Pivot * @return Pivot
* @throws Exception * @throws Exception
*/ */
protected function newPivot($data = []) protected function newPivot($data = [], $isUpdate = false)
{ {
$class = $this->pivotName ?: '\\think\\model\\Pivot'; $class = $this->pivotName ?: '\\think\\model\\Pivot';
$pivot = new $class($data, $this->parent, $this->middle); $pivot = new $class($data, $this->parent, $this->middle);
if ($pivot instanceof Pivot) { if ($pivot instanceof Pivot) {
return $pivot; return $isUpdate ? $pivot->isUpdate(true, $this->getUpdateWhere($data)) : $pivot;
} else { } else {
throw new Exception('pivot model must extends: \think\model\Pivot'); throw new Exception('pivot model must extends: \think\model\Pivot');
} }
@@ -117,7 +118,7 @@ class BelongsToMany extends Relation
} }
} }
} }
$model->setRelation('pivot', $this->newPivot($pivot)->isUpdate(true, $this->getUpdateWhere($pivot))); $model->setRelation('pivot', $this->newPivot($pivot, true));
} }
} }
@@ -383,7 +384,7 @@ class BelongsToMany extends Relation
} }
} }
} }
$set->setRelation('pivot', $this->newPivot($pivot)->isUpdate(true, $this->getUpdateWhere($pivot))); $set->setRelation('pivot', $this->newPivot($pivot, true));
$data[$pivot[$this->localKey]][] = $set; $data[$pivot[$this->localKey]][] = $set;
} }
return $data; return $data;
@@ -486,7 +487,7 @@ class BelongsToMany extends Relation
foreach ($ids as $id) { foreach ($ids as $id) {
$pivot[$this->foreignKey] = $id; $pivot[$this->foreignKey] = $id;
$this->pivot->insert($pivot, true); $this->pivot->insert($pivot, true);
$result[] = $this->newPivot($pivot)->isUpdate(true, $this->getUpdateWhere($pivot)); $result[] = $this->newPivot($pivot, true);
} }
if (count($result) == 1) { if (count($result) == 1) {
// 返回中间表模型对象 // 返回中间表模型对象