改进together方法支持传入关联模型数据

This commit is contained in:
thinkphp
2017-04-17 13:40:21 +08:00
parent 9b353811af
commit 04cf8a34e3

View File

@@ -894,7 +894,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
if (!empty($this->relationWrite)) { if (!empty($this->relationWrite)) {
$relation = []; $relation = [];
foreach ($this->relationWrite as $key => $name) { foreach ($this->relationWrite as $key => $name) {
if (!is_numeric($key)) { if (is_array($name)) {
if (key($name) === 0) {
$relation[$key] = []; $relation[$key] = [];
foreach ($name as $val) { foreach ($name as $val) {
if (isset($this->data[$val])) { if (isset($this->data[$val])) {
@@ -902,6 +903,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
unset($this->data[$val]); unset($this->data[$val]);
} }
} }
} else {
$relation[$key] = $name;
}
} elseif (isset($this->relation[$name])) { } elseif (isset($this->relation[$name])) {
$relation[$name] = $this->relation[$name]; $relation[$name] = $this->relation[$name];
} }
@@ -943,17 +947,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
if (empty($data) || (count($data) == 1 && is_string($pk) && isset($data[$pk]))) { if (empty($data) || (count($data) == 1 && is_string($pk) && isset($data[$pk]))) {
// 关联更新 // 关联更新
if (isset($relation)) { if (isset($relation)) {
foreach ($relation as $name => $val) { $this->autoRelationUpdate($relation);
if ($val instanceof Model) {
$val->save();
} else {
unset($this->data[$name]);
$model = $this->getAttr($name);
if ($model instanceof Model) {
$model->save($val);
}
}
}
} }
return 0; return 0;
} elseif ($this->autoWriteTimestamp && $this->updateTime && !isset($data[$this->updateTime])) { } elseif ($this->autoWriteTimestamp && $this->updateTime && !isset($data[$this->updateTime])) {
@@ -985,17 +979,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
// 关联更新 // 关联更新
if (isset($relation)) { if (isset($relation)) {
foreach ($relation as $name => $val) { $this->autoRelationUpdate($relation);
if ($val instanceof Model) {
$val->save();
} else {
unset($this->data[$name]);
$model = $this->getAttr($name);
if ($model instanceof Model) {
$model->save($val);
}
}
}
} }
// 更新回调 // 更新回调
@@ -1051,6 +1035,21 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
return $result; return $result;
} }
protected function autoRelationUpdate($relation)
{
foreach ($relation as $name => $val) {
if ($val instanceof Model) {
$val->save();
} else {
unset($this->data[$name]);
$model = $this->getAttr($name);
if ($model instanceof Model) {
$model->save($val);
}
}
}
}
/** /**
* 获取变化的数据 并排除只读数据 * 获取变化的数据 并排除只读数据
* @access public * @access public