Skip to content

Commit 0cb444c

Browse files
committed
修正关联更新问题
1 parent 6c7caf3 commit 0cb444c

File tree

3 files changed

+7
-10
lines changed

3 files changed

+7
-10
lines changed

src/Model.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ public function save(array | object $data = [], $where = []): bool
318318

319319

320320
foreach ($data as $name => &$val) {
321-
if ($val instanceof Model) {
321+
if ($val instanceof Modelable) {
322322
$relations[$name] = $val;
323323
unset($data[$name]);
324324
} elseif ($val instanceof Collection || !in_array($name, $allow)) {
@@ -351,7 +351,7 @@ public function save(array | object $data = [], $where = []): bool
351351

352352
// 保存关联数据
353353
if (!empty($relations)) {
354-
$this->relationSave($relations);
354+
$this->relationSave($relations, $isUpdate);
355355
}
356356

357357
// 重置原始数据

src/model/concern/RelationShip.php

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,17 +107,14 @@ public function getRelation(string $relation): array
107107
* 写入模型关联数据(一对一).
108108
*
109109
* @param array $relations 数据
110+
* @param bool $isUpdate 是否更新
110111
* @return void
111112
*/
112-
private function relationSave(array $relations = [])
113+
private function relationSave(array $relations = [], bool $isUpdate = true)
113114
{
114115
foreach ($relations as $name => $relation) {
115116
if ($relation && in_array($name, $this->getOption('together'))) {
116-
$relationKey = $this->getRelationKey($name);
117-
if ($relationKey) {
118-
$relation->$relationKey = $this->getKey();
119-
}
120-
$relation->save();
117+
$isUpdate ? $relation->save() : $this->$name()->save($relation);
121118
}
122119
}
123120
}

tests/orm/ModelFieldTypeTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,13 @@ public function testFieldTypeSelect()
5757
public function testFieldReadAndWrite()
5858
{
5959
/** @var FieldTypeModel $result */
60-
$result = FieldTypeModel::query()->where('id', '=', 3)->find();
60+
$result = FieldTypeModel::where('id', '=', 3)->find();
6161
$result->t_json = new TestFieldJsonDTO(30, 'ddd');
6262
$result->t_php = new TestFieldPhpDTO(40, 'eee');
6363
$result->save();
6464

6565
/** @var FieldTypeModel $result */
66-
$result = FieldTypeModel::query()->where('id', '=', 3)->find();
66+
$result = FieldTypeModel::where('id', '=', 3)->find();
6767
$this->assertEquals(new TestFieldJsonDTO(30, 'ddd'), $result->t_json);
6868
$this->assertEquals((string) new TestFieldPhpDTO(40, 'eee'), (string) $result->t_php);
6969
$this->assertEquals($result->id, $result->t_php->getId());

0 commit comments

Comments
 (0)