Laravel全球范围与关系

时间:2015-09-07 09:20:24

标签: php laravel scope relationship

我想要一个具有全局查询范围的模型,该模型的范围是多态的一对一关系。

问题是一切正常,我可以创建全局查询范围,但我没有在全局查询范围类的apply函数中获得关系。我想用关系进行查询,而不是仅仅进行连接查询或其他。

有人知道这是否可能?

我有以下代码:

class Content extends Model {
    use Environmentabletrait;
}

trait EnvironmentableTrait {
    public static function bootEnvironmentableTrait() {
        static::addGlobalScope(new EnvironmentScope);
    }

    public function environment() {
        return $this->morphOne(Environment::class, 'environmentable');
    }
}

class Environment extends Model {
    public function environmentable() {
        return $this->morphTo();
    }
}

class EnvironmentScope implements ScopeInterface {
    public function apply(Builder $builder, Model $model) {
        $builder-> ...
    }
}

并且

我希望我已经解释得很好;)

非常感谢提前

1 个答案:

答案 0 :(得分:2)

没关系,我已使用以下代码修复它:

public function apply(Builder $builder, Model $model)
{
    return $builder->whereHas('environment', function ($query) {
        $query->where('environment', app()->environment());
    });
}
相关问题