From 961b577c179e9d79e2df6d8ad131f7ac5de35895 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 24 Dec 2024 15:03:41 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E4=BD=93=E6=A8=A1=E5=9E=8B=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E8=87=AA=E5=8A=A8=E5=86=99=E5=85=A5=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Entity.php | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/Entity.php b/src/Entity.php index e0582095..5c949cd2 100644 --- a/src/Entity.php +++ b/src/Entity.php @@ -15,6 +15,7 @@ use ArrayAccess; use BackedEnum; +use Closure; use InvalidArgumentException; use JsonSerializable; use Stringable; @@ -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'] ?? [], ]; @@ -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); @@ -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); + } + } + } + } + /** * 获取当前时间. *