首页
/ 深入理解Eloquent Has Many Deep中的软删除中间表处理

深入理解Eloquent Has Many Deep中的软删除中间表处理

2025-06-28 05:16:29作者:冯梦姬Eddie

在Laravel开发中,Eloquent ORM提供了强大的关系处理能力,而staudenmeir/eloquent-has-many-deep扩展包则进一步增强了这种能力,允许开发者定义和处理深度嵌套的关系。本文将重点探讨在该扩展包中如何处理中间表的软删除问题。

问题背景

当使用eloquent-has-many-deep处理多层级关系时,经常会遇到中间表也实现了软删除功能的情况。默认情况下,Eloquent会自动过滤掉已被软删除的记录,这在某些场景下可能不是我们想要的行为。

关系定义分析

典型的深度关系定义如下:

class Organisation
{
    public function level2Stock()
    {
        return $this->hasManyDeep(
            StoresLevel2Stock::class,
            [
                Stores::class,
                StoresCategory::class,
                StoresLevel1::class,
                StoresLevel2::class,
            ]
        )
            ->withIntermediate(Stores::class, ['id'])
            ->withIntermediate(StoresCategory::class, ['id'])
            ->withIntermediate(StoresLevel1::class, ['id'])
            ->withIntermediate(StoresLevel2::class, ['id']);
    }
}

反向关系查询

在反向查询时,我们可能希望包含所有中间表的记录,包括被软删除的:

class Stock
{
    public function parents()
    {
        return $this->hasOneDeepFromReverse(
            (new Organisation())->level2Stock()
        )
            ->withIntermediate(Stores::class, ['id'])
            ->withIntermediate(StoresCategory::class, ['id'])
            ->withIntermediate(StoresLevel1::class, ['id'])
            ->withIntermediate(StoresLevel2::class, ['id']);
    }
}

软删除处理挑战

默认情况下,查询会自动添加软删除条件,导致只返回未被删除的记录。尝试使用以下方法可能无法达到预期效果:

$relation->withoutGlobalScopes([SoftDeletingScope::class]);
foreach ($intermediateTables as $intermediateTable => $columns) {
    $relation->withTrashed("$intermediateTable.deleted_at");
}

解决方案

经过深入分析,发现需要显式移除每个中间表的软删除全局作用域:

$relation->withoutGlobalScope('Staudenmeir\EloquentHasManyDeep\HasManyDeep:stores.deleted_at');
$relation->withoutGlobalScope('Staudenmeir\EloquentHasManyDeep\HasManyDeep:store_categories.deleted_at');
$relation->withoutGlobalScope('Staudenmeir\EloquentHasManyDeep\HasManyDeep:store_level1s.deleted_at');
$relation->withoutGlobalScope('Staudenmeir\EloquentHasManyDeep\HasManyDeep:store_level2s.deleted_at');

技术原理

eloquent-has-many-deep扩展包为每个中间表的软删除字段创建了独立的全局作用域。这些作用域以特定格式命名,包含表名和字段名。因此,简单地移除SoftDeletingScope类并不能完全禁用所有中间表的软删除过滤。

最佳实践

  1. 明确识别所有中间表的软删除作用域
  2. 按名称逐个移除这些作用域
  3. 在需要时重新启用特定作用域
  4. 考虑封装成可复用的方法,简化调用

总结

处理eloquent-has-many-deep中的中间表软删除需要特别注意其独特的作用域命名机制。通过理解这一机制,开发者可以更灵活地控制查询行为,满足各种业务场景的需求。

登录后查看全文
热门项目推荐
相关项目推荐