2017-10-13 67 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