首页 > 解决方案 > 雄辩的递归渴望关系需要了解范围

问题描述

我有一个从父查询调用的递归关系,如下所示:

$results = SomeModel::with(['children' => function($q) {
        $q->enabledOnlyBool(true);
    }])
    ->get();

里面SomeModel我有关系:

public function children(): HasMany {
    return $this->hasMany(__CLASS__, 'parent_id', 'id')
        ->with('children');
}

在那个关系调用中,有没有办法知道全局范围scopeEnabledOnlyBool($bool)已应用于父模型?要以递归方式急切加载,了解应用于初始调用的范围将是真正有意义的。

我最接近的方法是找到该方法\Illuminate\Database\Eloquent\Model::hasNamedScope($scope),但是它似乎只在范围存在时才返回 true,而不是它是否被应用。

理想情况下,我希望能够执行以下操作:

public function children(): HasMany {
    return $this->hasMany(__CLASS__, 'parent_id', 'id')
        ->with(['children' => function($q) {
            if ($whatever) {
                // Apply scope
            }
        }]);
}

标签: phplaraveleloquent

解决方案


推荐阅读