diff --git a/src/Entity.php b/src/Entity.php index 95e2844b..2c1f0c7a 100644 --- a/src/Entity.php +++ b/src/Entity.php @@ -64,6 +64,7 @@ public function __construct(array | object $data = [], ?Model $model = null) 'origin' => [], 'schema' => [], 'together' => [], + 'allow' => [], 'hidden' => $options['hidden'] ?? [], 'visible' => $options['visible'] ?? [], 'append' => $options['append'] ?? [], @@ -348,6 +349,20 @@ public function together(array $relation) return $this; } + /** + * 允许写入字段. + * + * @param array $allow 允许字段 + * + * @return $this + */ + public function allow(array $allow) + { + $this->setWeakData('allow', $allow); + + return $this; + } + /** * 强制写入或删除 * @@ -482,6 +497,7 @@ public function save(array | object $data = []): bool $data = $this->getData(); $origin = $this->getOrigin(); + $allow = $this->getWeakData('allow'); $isUpdate = $this->model()->getKey() && !$this->model()->isForce(); foreach ($data as $name => &$val) { @@ -490,6 +506,8 @@ public function save(array | object $data = []): bool unset($data[$name]); } elseif ($val instanceof Collection) { unset($data[$name]); + } elseif (!empty($allow) && !in_array($name, $allow)) { + unset($data[$name]); } elseif ($isUpdate && ((isset($origin[$name]) && $val === $origin[$name]) || $this->model()->getPk() == $name)) { unset($data[$name]); } else { @@ -599,13 +617,45 @@ public function delete(): bool * 写入数据. * * @param array|object $data 数据 + * @param array $allowField 允许字段 + * @param bool $replace 使用Replace + * @return static + */ + public static function create(array | object $data, array $allowField = [], bool $replace = false): Entity + { + $model = new static(); + + if (!empty($allowField)) { + $model->allow($allowField); + } + + $model->replace($replace); + $model->save($data); + + return $model; + } + + /** + * 写入数据. * + * @param array|object $data 数据 + * @param mixed $where 更新条件 + * @param array $allowField 允许字段 * @return static */ - public static function create(array | object $data): Entity + public static function update(array | object $data, $where = [], array $allowField = []): Entity { $model = new static(); + if (!empty($allowField)) { + $model->allow($allowField); + } + + if (!empty($where)) { + $model->setUpdateWhere($where); + } + + $model->exists(true); $model->save($data); return $model; @@ -669,10 +719,14 @@ function getPublicVars($object) /** * 获取原始数据. * + * @param string|null $name 字段名 * @return array */ - public function getOrigin(): array + public function getOrigin(?string $name = null): array { + if ($name) { + return self::$weakMap[$this]['origin'][$name] ?? null; + } return self::$weakMap[$this]['origin']; } @@ -807,7 +861,7 @@ public function get(string $name) return $value; } - public function getValue(string $name) + private function getValue(string $name) { if ($this->isStrictMode()) { return $this->$name ?? null;