Skip to content

Commit

Permalink
调整字段命名规范
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Nov 19, 2024
1 parent f523a17 commit 122adae
Showing 1 changed file with 36 additions and 20 deletions.
56 changes: 36 additions & 20 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,19 @@ public function __construct(array | object $data = [], ?Model $model = null)
}

self::$weakMap[$this] = [
'get' => [],
'data' => [],
'origin' => [],
'schema' => [],
'together' => [],
'allow' => [],
'hidden' => $options['hidden'] ?? [],
'visible' => $options['visible'] ?? [],
'append' => $options['append'] ?? [],
'mapping' => $options['mapping'] ?? [],
'strict' => true,
'model' => $model,
'model' => $model,
'get' => [],
'data' => [],
'origin' => [],
'schema' => [],
'together' => [],
'allow' => [],
'strict_mode' => true,
'hidden' => $options['hidden'] ?? [],
'visible' => $options['visible'] ?? [],
'append' => $options['append'] ?? [],
'mapping' => $options['mapping'] ?? [],
'strict' => $options['strict'] ?? true,
];

$model->setEntity($this);
Expand Down Expand Up @@ -133,18 +134,17 @@ protected function initializeData(array | object $data, bool $fromSave = false)
}
}
$trueName = $this->getRealFieldName($name);
if ($this->model()->getPk() == $trueName) {
// 记录主键值
$this->model()->setKey($val);
}
if (in_array($trueName, $fields)) {
// 读取数据后进行类型转换
$value = $this->readTransform($val, $schema[$trueName] ?? 'string');

$this->$trueName = $value;
$origin[$trueName] = $value;
}

if ($this->model()->getPk() == $trueName) {
// 记录主键值
$this->model()->setKey($val);
}
}

if (!empty($origin)) {
Expand Down Expand Up @@ -180,12 +180,16 @@ protected function setData($key, $name, $value)

protected function getRealFieldName(string $name)
{
return self::$weakMap[$this]['model']->getRealFieldName($name);
if (!self::$weakMap[$this]['strict']) {
return Str::camel($name);
}

return $name;
}

protected function isStrictMode(): bool
{
return self::$weakMap[$this]['strict'];
return self::$weakMap[$this]['strict_mode'];
}

/**
Expand Down Expand Up @@ -301,7 +305,7 @@ protected function getFields(?string $field = null)

if (empty($schema)) {
// 采用非严格模式
$this->setWeakData('strict', false);
$this->setWeakData('strict_mode', false);
// 获取数据表信息
$schema = $weakMap['model']->getFieldsType($weakMap['model']->getTable());
$type = $weakMap['model']->getType();
Expand Down Expand Up @@ -521,6 +525,18 @@ public function save(array | object $data = []): bool
}
}

if (!self::$weakMap[$this]['strict']) {
// 非严格模式下 自动转换为小写下划线规范
foreach ($data as $name => $val) {
// 属性名称转换
$trueName = Str::snake($name);
if ($trueName != $name) {
$data[$trueName] = $val;
unset($data[$name]);
}
}
}

$result = $this->model()->save($data);

if (false === $result) {
Expand Down

0 comments on commit 122adae

Please sign in to comment.