Laravel 5具有动态参数的全局范围 [英] Laravel 5 Global Scope with Dynamic Parameter

查看:67
本文介绍了Laravel 5具有动态参数的全局范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用带有动态查询参数的全局范围时,我们遇到了问题.全局作用域基于管理者ID,但是$ model为空,并且$ this指的是管理者作用域而不是模型,因此$ this-> id是未定义的属性.有没有办法做这样的事情:

We're having issues using a global scope with a dynamic query parameter. The global scope is based on the manager ID, but $model is empty, and $this refers to the manager scope not the model so $this->id is an undefined property. Is there a way to do something like this:

public function apply(Builder $builder, Model $model)
{
    return $builder->where('manager', $model->id); // $this->id
}

我假设 $ model 应该是经理模型,但是由于它是空的,而且我找不到关于它的任何文档,所以我不确定(如果有人可以在评论中告诉我,我将不胜感激.这是Manager模型中的全局范围方法:

I'm assuming that $model is supposed to be the manager model, but since it is empty and I can't find any documentation on it I'm not entirely sure (if anyone can tell me in a comment I'd appreciate it). This is our global scope method in the Manager model:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope(new ManagerScope);
}

由于全局范围不需要应用显式方法,我想也许在引导中添加一些内容可能会允许一个额外的参数,例如:

Since global scopes don't require an explicit method to be applied I thought maybe adding something to the boot might allow for an extra parameter something like:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope(new ManagerScope($this->id);
}

但是在静态方法中不允许这样做,这在我看到错误后才有意义.

But this isn't allowed in a static method, which makes sense after I saw the error.

推荐答案

自然,全局范围会自动应用,并且无法直接将参数传递给它们.

Naturally global scopes are applied automatically and there are no way to pass parameters to them directly.

因此,您可以坚持使用动态局部范围,这对IMO来说更有意义,

Therefore you can either stick with a dynamic local scope, which IMO makes more sense,

public function scopeForManager($query, $manager)
{
    return $query->where('manager', $manager->id);
}

Document::forManager($manager)->all();

,或者如果经理信息在某种全局状态下(即会话)可用,则可以创建某种ManagerResolver类

or if the a manager info is available in some kind of global state (i.e. session) you can create some sort of ManagerResolver class

class ManagerScope
{
    protected $resolver;

    public function __construct(ManagerResolver $resolver)
    {
        $this->resolver = $resolver
    }

    public function apply(Builder $builder, Model $model)
    {
        return $builder->where('manager', $this->resolver->getManagerId());
    }    
}

并将其实例传递到您的作用域

and pass an instance of it into your scope

protected static function boot()
{
    parent::boot();
    static::addGlobalScope(new ManagerScope(new ManagerResolver());
}

这篇关于Laravel 5具有动态参数的全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆