Skip to content

Commit

Permalink
实体模型的save和delete直接调用模型方法
Browse files Browse the repository at this point in the history
  • Loading branch information
liu21st committed Nov 18, 2024
1 parent 4fc458b commit bb121c2
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 114 deletions.
118 changes: 27 additions & 91 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ public function __construct(array | object $data = [], ?Model $model = null)
];

$model->setEntity($this);
$model->exists(true);

$this->initializeData($data);
}
Expand Down Expand Up @@ -104,11 +103,14 @@ protected function initializeData(array | object $data)
}
}

$this->setWeakData('origin', $origin);
if (!empty($origin)) {
$this->model()->exists(true);
$this->setWeakData('origin', $origin);

if (!self::$weakMap[$this]['strict']) {
// 非严格定义模式下 采用动态属性
$this->setWeakData('data', $origin);
if (!self::$weakMap[$this]['strict']) {
// 非严格定义模式下 采用动态属性
$this->setWeakData('data', $origin);
}
}
}

Expand Down Expand Up @@ -325,27 +327,23 @@ public function save(array | object $data = []): bool
return true;
}

$weakMap = self::$weakMap[$this];
if (!empty($data)) {
$data = $this->parseData($data);
$this->initializeData($data);
} else {
$data = $this->getData($this);
}

if (empty($data) || false === $weakMap['model']->trigger('BeforeWrite')) {
return false;
}

$isUpdate = $weakMap['model']->getKey();
$origin = self::$weakMap[$this]['origin'];
$isUpdate = $this->model()->getKey();

foreach ($data as $name => &$val) {
if ($val instanceof Entity) {
$relations[$name] = $val;
unset($data[$name]);
} elseif ($val instanceof Collection) {
unset($data[$name]);
} elseif (!$isUpdate || (isset($weakMap['origin'][$name]) && $val !== $weakMap['origin'][$name])) {
} elseif (!$isUpdate || (isset($origin[$name]) && $val !== $origin[$name])) {
// 类型转换
$val = $this->writeTransform($val, $this->getFields($name));
$method = 'set' . Str::studly($name) . 'Attr';
Expand All @@ -358,15 +356,12 @@ public function save(array | object $data = []): bool
}
}

$result = $isUpdate ? $this->updateData($weakMap['model'], $data) : $this->insertData($weakMap['model'], $data);
$result = $this->model()->save($data);

if (false === $result) {
return false;
}

// 写入回调
$weakMap['model']->trigger('AfterWrite');

// 保存关联数据
if (!empty($relations)) {
$this->relationSave($relations);
Expand All @@ -375,79 +370,6 @@ public function save(array | object $data = []): bool
return true;
}

/**
* 新增数据.
*
* @param Model $model 模型对象
* @param array $data 数据
* @return bool
*/
protected function insertData(Model $model, array $data): bool
{
// 主键自动写入
if ($model->isAutoWriteId()) {
$pk = $model->getPk();
if (is_string($pk) && !isset($data[$pk])) {
$data[$pk] = $model->autoWriteId();
}
}

if (empty($data) || false === $model->trigger('BeforeInsert')) {
return false;
}

// 时间字段自动写入
foreach ($model->getDateTimeFields() as $field) {
if (is_string($field)) {
$type = $this->getFields($field);
if (is_subclass_of($type, Typeable::class)) {
$data[$field] = $type::from('now', $this)->value();
$this->$field = $data[$field];
}
}
}

$fields = array_keys($this->getFields());
$result = $model->db()->field($fields)->insert($data, true);

$this->setKey($result);
$model->setKey($result);
$model->trigger('AfterInsert');
return true;
}

/**
* 更新数据.
*
* @param Model $model 模型对象
* @param array $data 数据
* @return bool
*/
protected function updateData(Model $model, array $data): bool
{
if (empty($data) || false === $model->trigger('BeforeUpdate')) {
return false;
}

// 时间字段自动更新
$field = $model->getDateTimeFields(true);
if (is_string($field)) {
$type = $this->getFields($field);
if (is_subclass_of($type, Typeable::class)) {
$data[$field] = $type::from('now', $this)->value();
$this->$field = $data[$field];
}
}

$model->db(null)
->where($model->getPk(), $model->getKey())
->update($data);

// 更新回调
$model->trigger('AfterUpdate');
return true;
}

/**
* 写入模型关联数据(一对一).
*
Expand Down Expand Up @@ -585,7 +507,7 @@ public static function destroy($data): bool
* @param int|string $value 值
* @return void
*/
protected function setKey($value)
public function setKey($value)
{
$pk = $this->model()->getPk();
if (is_string($pk)) {
Expand Down Expand Up @@ -624,7 +546,7 @@ function getPublicVars($object)
*/
public function toArray(array $allow = []): array
{
$data = $this->getdata();
$data = $this->getData();
foreach ($data as $name => &$item) {
if (!empty($allow) && !in_array($name, $allow)) {
unset($data[$name]);
Expand Down Expand Up @@ -768,6 +690,20 @@ public function __toString()
return $this->toJson();
}

public function __debugInfo()
{
if (!self::$weakMap[$this]['strict']) {
return [
'data' => self::$weakMap[$this]['data'],
'schema' => self::$weakMap[$this]['schema'],
];
} else {
return [
'schema' => self::$weakMap[$this]['schema'],
];
}
}

// JsonSerializable
public function jsonSerialize(): array
{
Expand Down
81 changes: 58 additions & 23 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
use JsonSerializable;
use think\contract\Arrayable;
use think\contract\Jsonable;
use think\model\contract\Modelable;
use think\db\BaseQuery as Query;
use think\model\contract\Modelable;

/**
* Class Model.
Expand Down Expand Up @@ -665,14 +665,17 @@ public function save(array | object $data = [], ?string $sequence = null): bool
$data = get_object_vars($data);
}

// 数据对象赋值
$this->setAttrs($data);
if (!$this->entity) {
// 数据对象赋值
$this->setAttrs($data);
$data = $this->data;
}

if ($this->isEmpty() || false === $this->trigger('BeforeWrite')) {
return false;
}

$result = $this->exists ? $this->updateData() : $this->insertData($sequence);
$result = $this->exists ? $this->updateData($data) : $this->insertData($data, $sequence);

if (false === $result) {
return false;
Expand All @@ -689,9 +692,11 @@ public function save(array | object $data = [], ?string $sequence = null): bool
$this->change = [];
}

// 重新记录原始数据
$this->origin = $this->data;
$this->get = [];
if (!$this->entity) {
// 重新记录原始数据
$this->origin = $this->data;
$this->get = [];
}

return true;
}
Expand All @@ -705,6 +710,10 @@ protected function checkAllowFields(): array
{
// 检测字段
if (empty($this->field)) {
if ($this->entity) {
return array_keys($this->entity->getFields());
}

if (!empty($this->schema)) {
$this->field = array_keys(array_merge($this->schema, $this->jsonType));
} else {
Expand Down Expand Up @@ -736,7 +745,7 @@ protected function checkAllowFields(): array
*
* @return bool
*/
protected function updateData(): bool
protected function updateData(array $data): bool
{
// 事件回调
if (false === $this->trigger('BeforeUpdate')) {
Expand All @@ -746,7 +755,9 @@ protected function updateData(): bool
$this->checkData();

// 获取有更新的数据
$data = $this->getChangedData($this->data);
if (!$this->entity) {
$data = $this->getChangedData($data);
}

if (empty($data)) {
// 关联更新
Expand All @@ -759,8 +770,13 @@ protected function updateData(): bool

if ($this->autoWriteTimestamp && $this->updateTime) {
// 自动写入更新时间
$data[$this->updateTime] = $this->autoWriteTimestamp();
$this->data[$this->updateTime] = $data[$this->updateTime];
$data[$this->updateTime] = $this->autoWriteTimestamp();
if ($this->entity) {
$updateTimeField = $this->updateTime;
$this->entity->$updateTimeField = $data[$this->updateTime];
} else {
$this->data[$this->updateTime] = $data[$this->updateTime];
}
}

// 检查允许字段
Expand All @@ -782,8 +798,8 @@ protected function updateData(): bool
$db = $this->db(null);

$db->transaction(function () use ($data, $allowFields, $db) {
$where = $this->getWhere();
$result = $db->where($where)
$where = $this->getWhere();
$result = $db->where($where)
->strict(false)
->cache(true)
->setOption('key', $this->key)
Expand Down Expand Up @@ -811,7 +827,7 @@ protected function updateData(): bool
*
* @return bool
*/
protected function insertData(?string $sequence = null): bool
protected function insertData(array $data, ?string $sequence = null): bool
{
if (false === $this->trigger('BeforeInsert')) {
return false;
Expand All @@ -823,15 +839,25 @@ protected function insertData(?string $sequence = null): bool
if ($this->isAutoWriteId()) {
$pk = $this->getPk();
if (is_string($pk) && !isset($this->data[$pk])) {
$this->data[$pk] = $this->autoWriteId();
$data[$pk] = $this->autoWriteId();
if ($this->entity) {
$this->entity->$pk = $data[$pk];
} else {
$this->data[$pk] = $data[$pk];
}
}
}

// 时间字段自动写入
if ($this->autoWriteTimestamp) {
foreach ([$this->createTime, $this->updateTime] as $field) {
if ($field && !array_key_exists($field, $this->data)) {
$this->data[$field] = $this->autoWriteTimestamp();
$data[$field] = $this->autoWriteTimestamp();
if ($this->entity) {
$this->entity->$field = $data[$field];
} else {
$this->data[$field] = $data[$field];
}
}
}
}
Expand All @@ -840,11 +866,17 @@ protected function insertData(?string $sequence = null): bool
if (!empty($this->insert)) {
foreach ($this->insert as $name => $val) {
$field = is_string($name) ? $name : $val;
if (!isset($this->data[$field])) {
if (!isset($data[$field])) {
if (is_string($name)) {
$this->data[$name] = $val;
$data[$field] = $val;
$this->data[$field] = $val;
} else {
$this->setAttr($field, null);
$data[$field] = $this->data[$field];
}

if ($this->entity) {
$this->entity->$field = $data[$field];
}
}
}
Expand All @@ -853,8 +885,7 @@ protected function insertData(?string $sequence = null): bool
// 检查允许字段
$allowFields = $this->checkAllowFields();

$db = $this->db();
$data = $this->data;
$db = $this->db();

$db->transaction(function () use ($data, $sequence, $allowFields, $db) {
$result = $db->strict(false)
Expand All @@ -867,9 +898,13 @@ protected function insertData(?string $sequence = null): bool
if ($result && !$this->isAutoWriteId()) {
$pk = $this->getPk();

if (is_string($pk) && (!isset($this->data[$pk]) || '' == $this->data[$pk])) {
unset($this->get[$pk]);
$this->data[$pk] = $result;
if (is_string($pk) && (!isset($data[$pk]) || '' == $data[$pk])) {
if ($this->entity) {
$this->entity->setKey($result);
} else {
unset($this->get[$pk]);
$this->data[$pk] = $result;
}
}
}

Expand Down

0 comments on commit bb121c2

Please sign in to comment.