Laravel 软删除功能概述
在 Laravel 中为模型启用软删除功能,必须引入 Illuminate\Database\Eloquent\SoftDeletes 特性类。该功能旨在满足以下核心需求:
执行删除操作时仅标记状态,不执行物理层面的数据清除。
进行常规查询时,系统自动排除已被标记为删除的记录。
支持灵活配置是否包含已删除数据,或专门检索已删除的数据集。
提供恢复已删除数据的功能接口。
Model 的软删除实现逻辑
Illuminate\Database\Eloquent\Model 中delete方法源码:
public function delete()
{
if (is_null($this->getKeyName())) {
throw new Exception('No primary key defined on model.');
}
if (! $this->exists) {
return;
}
if ($this->fireModelEvent('deleting') === false) {
return false;
}
$this->touchOwners();
$this->performDeleteOnModel();
$this->fireModelEvent('deleted', false);
return true;
}
protected function performDeleteOnModel()
{
$this->setKeysForSaveQuery($this->newModelQuery())
->delete();
$this->exists = false;
}
由于子类引入了 SoftDeletes 特性, SoftDeletes 中的 performDeleteOnModel 方法会覆盖父类对应实现,最终调用 runSoftDelete 方法来更新删除标记字段。
protected function performDeleteOnModel()
{
if ($this->forceDeleting) {
$this->exists = false;
return $this->newModelQuery()->where(
$this->getKeyName(), $this->getKey()
)->forceDelete();
}
return $this->runSoftDelete();
}
protected function runSoftDelete()
{
$query = $this->newModelQuery()
->where($this->getKeyName(), $this->getKey());
$time = $this->freshTimestamp();
$columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];
$this->{$this->getDeletedAtColumn()} = $time;
if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
$this->{$this->getUpdatedAtColumn()} = $time;
$columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
}
$query->update($columns);
}
Model 查询时的数据过滤机制
Laravel 允许在 Model 中通过 static::addGlobalScope 添加全局 Scope,从而在查询条件中注入全局约束。软删除的数据过滤正是基于此机制实现的。
SoftDeletes 特性注册了 Illuminate\Database\Eloquent\SoftDeletingScope 全局 Scope。在该 Scope 内部实现了自动过滤被删除数据的逻辑,并支持指定查询已删除数据的功能。
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
远程关联数据的软删除处理
Scope 的作用范围仅限于当前模型及其直接关联模型。对于远程关联(如 hasManyThrough),还需额外处理。Laravel 通过 hasManyThrough 实现远程关联,其中涉及两处软删除查询逻辑。
protected function performJoin(Builder $query = null)
{
$query = $query ?: $this->query;
$farKey = $this->getQualifiedFarKeyName();
$query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $farKey);
if ($this->throughParentSoftDeletes()) {
$query->whereNull(
$this->throughParent->getQualifiedDeletedAtColumn()
);
}
}
public function throughParentSoftDeletes()
{
return in_array(SoftDeletes::class, class_uses_recursive(
get_class($this->throughParent)
));
}
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$query->from( $query->getModel()->getTable().' as '
.$hash = $this->getRelationCountHash()
);
$query->join($this->throughParent->getTable(),
$this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->secondLocalKey
);
if ($this->throughParentSoftDeletes()) {
$query->whereNull($this->throughParent->getQualifiedDeletedAtColumn());
}
$query->getModel()->setTable($hash);
return $query->select($columns)->whereColumn(
$parentQuery->getQuery()->from.'.'.$query->getModel()->getKeyName(), '=', $this->getQualifiedFirstKeyName()
);
}
在 performJoin 方法中,通过中间模型关联远程模型时,会根据 throughParentSoftDeletes 判断中间模型是否存在软删除。若存在,则过滤掉中间模型中被删除的数据。
上述即为 Laravel 软删除的大致逻辑。需注意一个细节:Laravel 软删除标记默认为时间格式字段,即 delete_at 。系统通过判断该字段是否为 null 来确定数据是否被删除。
然而,部分项目可能使用整形字段来标记数据删除状态。在此场景下,需对 Laravel 原有的软删除机制进行修改以适应需求。
主要解决方案如下:
1. 自定义 SoftDeletes 特性,修改字段名称及更新删除标记的操作逻辑;
2. 自定义 SoftDeletingScope,调整查询条件以适配新的标记字段;
3. 自定义 HasRelationships 特性,在其中重写 newHasManyThrough 方法,实例化自定义的 HasManyThrough 对象。
总结
以上介绍了 Laravel 实现数据软删除功能的原理及自定义方法,希望能帮助开发者解决相关问题。如有任何疑问,欢迎留言交流,小编将及时回复。