2015-09-07 67 views
1

我想要一个全局查询范围的模型,其范围在多态一对一关系上。Laravel与关系的全球范围

事情是,一切正常,我可以创建全局查询范围,但我没有得到全局查询范围类中的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

没关系,我我用下面的代码修正了它:

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