2017-10-13 95 views
0

User類中有兩個方法返回不同的查詢。我想用兩個這樣Laravel:concat多個模型查詢

$users = User::fromCountry('DE') 
        ->isMaster() 
        ->paginate(20); 

,但它是不工作的,因爲isMaster()是從User的方法,而不是從查詢生成器:

調用未定義的方法照亮\數據庫\查詢\生成器:: isMaster()

我也試過

$users = User::fromCountry('DE') 
        ->(User::isMaster()) 
        ->paginate(20); 

但這也不起作用。是否可以輕鬆地將User課程中的查詢結合起來?


以防萬一它的必要,這裏有來自User類中的兩個方法:

public static function isMaster() 
    { 
     switch (orga) { 
     case 1: 
      return static::where('modeIN','=','MT'); 

     case 2: 
      return static::where('modeICI','=','CMT'); 

     case 3: 
      return static::where('modeWHO','=','HMT'); 
     } 
    } 


    public static function fromCountry($country) 
    { 
     return static::where(
       function($query) use($country){ 
       $query->whereHas('addresses', 
          function($q) use($country){ 
          $q->where('idCountry','=',$country); 
          } 
         ) 
         ->orWhereHas('institutes', 
         function($q) use($country){ 
          $q->whereHas('addresses', 
          function($q) use($country){ 
           $q->where('idCountry','=',$country); 
          }); 
         } 
        ); 
      }); 
    } 

回答

1

試着改變你的模式功能:

public function scopeIsMaster($query) 
    { 
     switch (orga) { 
     case 1: 
      return $query->where('modeIN','=','MT'); 

     case 2: 
      return $query->where('modeICI','=','CMT'); 

     case 3: 
      return $query->where('modeWHO','=','HMT'); 
     } 
    } 

public function scopeFromCountry($query,$country) 
    { 
     return $query->where(
       function($query) use($country){ 
       $query->whereHas('addresses', 
          function($q) use($country){ 
          $q->where('idCountry','=',$country); 
          } 
         ) 
         ->orWhereHas('institutes', 
         function($q) use($country){ 
          $q->whereHas('addresses', 
          function($q) use($country){ 
           $q->where('idCountry','=',$country); 
          }); 
         } 
        ); 
      }); 
    } 
+0

你不能讓它靜態的目的是什麼?我是否理解,我必須將查詢調用分成兩個調用:'$ users = User :: fromCountry('DE'); '和'$ users = User :: queryIsMaster($ users) - > paginate(20);'? – Adam

+0

不,你只需調用'$ users = User :: fromCountry('DE') - > isMaster() - > paginate(20);' – madalinivascu

1

這就是你可以做的。 Laravel使用範圍這樣的東西

User { 

    public function scopeOfType($query, $orga) 
    { 
     switch ($orga) { 
     case 1: 
      return $query->where('modeIN','=','MT'); 

     case 2: 
      return $query->where('modeICI','=','CMT'); 

     case 3: 
      return $query->where('modeWHO','=','HMT'); 
     } 
    } 


} 

然後像這樣調用它。

User::ofType(1); 
User::ofType(2); 
User::ofType(3); 

欲瞭解更多信息檢查https://laravel.com/docs/5.3/eloquent#local-scopes