Решение JacupoStanchis , на мой взгляд, не является полным.
Отношения не обрабатываются методами runSoftDelete
и restore
новой черты.
Предположим, у вас есть простое отношение, например:
Author 1-n Book
Рабочий пример:
$Author->delete();
$Author->restore();
Не рабочий пример:
$Book->author()->delete();
$Book->author()->restore();
Благодаря Xdebug я смог найти решение для «неработающего примера».
Кстати.В моем случае был нужен строковый столбец, чтобы я мог использовать уникальное ограничение в сочетании с удаленным состоянием.Таким образом, методы отличаются.
app/Traits/SoftDeletes.php
<?php
namespace App\Traits;
use App\Overrides\Eloquent\SoftDeletingScope;
trait SoftDeletes
{
use \Illuminate\Database\Eloquent\SoftDeletes;
/**
* Boot the soft deleting trait for a model.
*
* @return void
*/
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
/**
* Perform the actual delete query on this model instance.
*
* @return void
*/
protected function runSoftDelete()
{
$query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());
$time = $this->freshTimestamp();
$columns = [
$this->getDeletedAtColumn() => $this->fromDateTime($time),
$this->getDeletedHashColumn() => uniqid(),
];
$this->{$this->getDeletedAtColumn()} = $time;
if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
$this->{$this->getUpdatedAtColumn()} = $time;
$columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
}
$query->update($columns);
}
/**
* Restore a soft-deleted model instance.
*
* @return bool|null
*/
public function restore()
{
// If the restoring event does not return false, we will proceed with this
// restore operation. Otherwise, we bail out so the developer will stop
// the restore totally. We will clear the deleted timestamp and save.
if ($this->fireModelEvent('restoring') === false) {
return false;
}
$this->{$this->getDeletedAtColumn()} = null;
$this->{$this->getDeletedHashColumn()} = '';
// Once we have saved the model, we will fire the "restored" event so this
// developer will do anything they need to after a restore operation is
// totally finished. Then we will return the result of the save call.
$this->exists = true;
$result = $this->save();
$this->fireModelEvent('restored', false);
return $result;
}
/**
* Get the name of the "deleted at" column.
*
* @return string
*/
public function getDeletedHashColumn()
{
return defined('static::DELETED_HASH') ? static::DELETED_HASH : 'deleted_hash';
}
}
app/Overrides/Eloquent/SoftDeletingScope.php
<?php
namespace App\Overrides\Eloquent;
use Illuminate\Database\Eloquent;
class SoftDeletingScope extends Eloquent\SoftDeletingScope
{
/**
* Extend the query builder with the needed functions.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
public function extend(Eloquent\Builder $builder)
{
foreach ($this->extensions as $extension) {
$this->{"add{$extension}"}($builder);
}
$builder->onDelete(function (Eloquent\Builder $builder) {
$deletedAtColumn = $this->getDeletedAtColumn($builder);
$deletedHashColumn = $builder->getModel()->getDeletedHashColumn();
return $builder->update([
$deletedAtColumn => $builder->getModel()->freshTimestampString(),
$deletedHashColumn => uniqid(),
]);
});
}
/**
* Add the restore extension to the builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return void
*/
protected function addRestore(Eloquent\Builder $builder)
{
$builder->macro('restore', function (Eloquent\Builder $builder) {
$builder->withTrashed();
return $builder->update([
$builder->getModel()->getDeletedAtColumn() => null,
$builder->getModel()->getDeletedHashColumn() => '',
]);
});
}
}
Я добавил метод bootSoftDeletes
к новой Черте, котораядобавляет пользовательский SoftDeletingScope
в глобальную область.