2015-09-07 108 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()); 
    }); 
}