Skip to content

Commit

Permalink
改进
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Dec 5, 2024
1 parent 2a3931a commit 69ac6a0
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ public function __construct(array | object $data = [], ?Model $model = null)
'together' => [],
'allow' => [],
'with_attr' => [],
'force' => false,
'update_time' => $options['update_time'] ?? 'update_time',
'create_time' => $options['create_time'] ?? 'create_time',
'table_name' => $options['table_name'] ?? '',
Expand Down Expand Up @@ -561,7 +562,11 @@ public function allowField(array $allow)
*/
public function force(bool $force = true)
{
$this->model()->force($force);
if ($this->model() instanceof Model) {
$this->model()->force($force);
} else {
self::$weakMap[$this]['force'] = $force;
}

return $this;
}
Expand Down Expand Up @@ -714,15 +719,12 @@ public function save(array | object $data = [], $where = []): bool
$readonly = $this->getWeakData('readonly');
$disuse = $this->getWeakData('disuse');
$allow = array_diff($allow, $readonly, $disuse);
$model = $this->model();

// 验证数据
$this->validate($data, $allow);

if (!empty($where)) {
$isUpdate = true;
} elseif ($model instanceof Model) {
$isUpdate = $this->getKey() && !$model->isForce();
} else {
$isUpdate = $this->getKey() ? true : false;
}
Expand All @@ -734,7 +736,7 @@ public function save(array | object $data = [], $where = []): bool
} elseif ($val instanceof Collection || !in_array($name, $allow)) {
// 禁止更新字段(包括只读、废弃和数据集)
unset($data[$name]);
} elseif ($isUpdate && $this->isNotRequireUpdate($name, $val, $origin)) {
} elseif ($isUpdate && !$this->isForce() && $this->isNotRequireUpdate($name, $val, $origin)) {
// 无需更新字段
unset($data[$name]);
} else {
Expand All @@ -749,6 +751,7 @@ public function save(array | object $data = [], $where = []): bool
// 自动时间戳处理
$this->autoDateTime($data, $isUpdate);

$model = $this->model();
if ($model instanceof Model) {
$result = $model->allowField($allow)->setUpdateWhere($where)->save($data);
} else {
Expand Down Expand Up @@ -843,7 +846,7 @@ protected function relationSave(array $relations = [])
if ($relation && in_array($name, $this->getWeakData('together'))) {
$relationKey = $this->getRelationKey($name);
if ($relationKey) {
$relation->$relationKey = $this->model()->getKey();
$relation->$relationKey = $this->getKey();
}
$relation->save();
}
Expand Down Expand Up @@ -1118,6 +1121,19 @@ public function isEmpty(): bool
return empty($this->getData());
}

/**
* 判断数据是否为空.
*
* @return bool
*/
public function isForce(): bool
{
if ($this->model() instanceof Model) {
return $this->model()->isForce();
}
return self::$weakMap[$this]['force'] ?? false;
}

/**
* 设置数据对象的值
*
Expand Down

0 comments on commit 69ac6a0

Please sign in to comment.