Skip to content

Commit

Permalink
实体模型增加自动写入数据功能
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Dec 24, 2024
1 parent 4248b05 commit 961b577
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use ArrayAccess;
use BackedEnum;
use Closure;
use InvalidArgumentException;
use JsonSerializable;
use Stringable;
Expand Down Expand Up @@ -84,6 +85,7 @@ public function __construct(array | object $data = [], ?Model $model = null)
'mapping' => $options['mapping'] ?? [],
'strict' => $options['strict'] ?? true,
'bind_attr' => $options['bind_attr'] ?? [],
'auto_insert' => $options['auto_insert'] ?? [],
'auto_relation' => $options['auto_relation'] ?? [],
'relation_keys' => $options['relation_keys'] ?? [],
];
Expand Down Expand Up @@ -757,6 +759,11 @@ public function save(array | object $data = [], $where = []): bool
// 自动时间戳处理
$this->autoDateTime($data, $isUpdate);

if (!$isUpdate) {
// 自动写入数据
$this->autoInsertData($data);
}

$model = $this->model();
if ($model instanceof Model) {
$result = $model->allowField($allow)->setUpdateWhere($where)->save($data);
Expand Down Expand Up @@ -805,6 +812,30 @@ protected function autoDateTime(array &$data, bool $update)
}
}

/**
* 字段自动写入.
*
* @param array $data 数据
* @return void
*/
protected function autoInsertData(array &$data)
{
if (!empty(self::$weakMap[$this]['auto_insert'])) {
foreach (self::$weakMap[$this]['auto_insert'] as $name => $val) {
$field = is_string($name) ? $name : $val;
if (!isset($data[$field])) {
if ($val instanceof Closure) {
$value = $val($this);
} else {
$value = is_string($name) ? $val : $this->setWithAttr($field, null, $data);
}
$data[$field] = $value;
$this->setData($field, $value);
}
}
}
}

/**
* 获取当前时间.
*
Expand Down

0 comments on commit 961b577

Please sign in to comment.