增加CamelCase 兼容Camel格式的字段

This commit is contained in:
marun 2020-03-04 15:55:26 +08:00
parent f0c5a5b7d4
commit 186867c37f

View File

@ -0,0 +1,61 @@
<?php
namespace Hyperf\Database\Model\Concerns;
use Hyperf\Utils\Str;
trait CamelCase
{
protected function keyTransform($key)
{
return Str::camel($key);
}
public function getAttribute($key)
{
return parent::getAttribute(Str::snake($key));
}
public function setAttribute($key, $value)
{
return parent::setAttribute(Str::snake($key), $value);
}
protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes)
{
foreach ($mutatedAttributes as $key) {
if (!array_key_exists($this->keyTransform($key), $attributes)) {
continue;
}
$attributes[$this->keyTransform($key)] = $this->mutateAttributeForArray(
$this->keyTransform($key), $attributes[$this->keyTransform($key)]
);
}
return $attributes;
}
public function jsonSerialize()
{
$array = [];
foreach ($this->toArray() as $key => $value) {
$array[$this->keyTransform($key)] = $value;
}
return $array;
}
public function toArray(): array
{
$array = [];
foreach (parent::toArray() as $key => $value) {
$array[$this->keyTransform($key)] = $value;
}
return $array;
}
public function toOriginalArray(): array
{
return parent::toArray();
}
}