Skip to content

Commit a8bebe2

Browse files
committed
视图模型支持关联数据写入
1 parent 08d0d4e commit a8bebe2

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/Entity.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,12 +308,18 @@ public static function __callStatic($method, $args)
308308
$db = $entity->model()->db();
309309
}
310310

311+
if ('with' != $method && !empty(self::$weakMap[$entity]['autoMapping'])) {
312+
// 自动关联查询
313+
$db->with(self::$weakMap[$entity]['autoMapping']);
314+
}
315+
311316
return call_user_func_array([$db, $method], $args);
312317
}
313318

314319
public function __call($method, $args)
315320
{
316321
// 调用Model类方法
317-
return call_user_func_array([$this->model(), $method], $args);
322+
$result = call_user_func_array([$this->model(), $method], $args);
323+
return $result instanceof Model ? $this : $result;
318324
}
319325
}

src/model/View.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,11 @@ private function fetchViewAttr(string $field)
106106
$value = null;
107107
foreach ($relations as $relation) {
108108
if ($model->$relation->hasData($field)) {
109-
$value = $model->$relation->$field;
109+
$value = $model->$relation->$field;
110+
$mapping = $this->getOption('autoMappingAlias', []);
111+
112+
$mapping[$field] = $relation . '->' . $field;
113+
$this->setOption('autoMappingAlias', $mapping);
110114
break;
111115
}
112116
}
@@ -295,12 +299,16 @@ protected function convertData(): array
295299
{
296300
// 获取实体属性
297301
$properties = $this->getEntityProperties();
302+
$mapping = $this->getOption('autoMappingAlias', []);
298303
$data = $this->getData();
299304
$item = [];
300305
foreach ($properties as $key => $field) {
301306
if (strpos($field, '->')) {
302307
[$relation, $field] = explode('->', $field);
303308
$item[$relation][$field] = $data[$key];
309+
} elseif (is_int($key) && isset($mapping[$field])) {
310+
[$relation] = explode('->', $mapping[$field]);
311+
$this->model()->$relation->$field = $data[$field];
304312
} else {
305313
$item[$field] = $data[is_int($key) ? $field : $key];
306314
}

0 commit comments

Comments
 (0)