2016-03-09 43 views
3

我试图根据有多少点的用户来获取排名表。Laravel得到一个关系列排序的模型集合

我的用户模型(简体):

namespace Gamify; 
class User extends Model 
{ 
    protected $table = 'users'; 

    public function points() 
    { 
     return $this->hasMany('Gamify\Point'); 
    } 

    public function scopeMember($query) 
    { 
     return $query->where('role', '=', 'default'); 
    } 
} 

而点模型是:

namespace Gamify; 
class Point extends Model 
{ 
    protected $table = 'points'; 

    protected $fillable = array(
     'points', 
     'description' 
    ); 

    public function user() 
    { 
     return $this->belongsTo('Gamify\User'); 
    } 
} 

我想获得与它的点的总和用户的集合,通过有序这笔钱。

像这样的东西(这个代码只是一个样机):

public static function getRanking($limitTopUsers = 10) 
{ 
    return User::member()->orderBy(sum('points'))->get(); 
} 

我一直在玩User::with()和范围,我尽量不使用DB::raw()

任何人都可以帮助我吗?提前致谢。

回答

0

基于@ nextt1的代码,这是我最后的办法:

用户的型号:

public function points() 
{ 
    return $this->hasMany('Gamify\Point') 
     ->selectRaw('sum(points) as sum, user_id') 
     ->groupBy('user_id'); 
} 

public function getExperiencePoints() 
{ 
    return $this->points()->sum('points'); 
} 

然后我创建了一个函数t O调用排名:

public static function getRanking($limitTopUsers = 10) 
{ 
    $users = User::Member()->with('points')->get(); 

    $users = $users->sortByDesc(function ($user) { 
     return $user->getExperiencePoints(); 
    })->take($limitTopUsers); 

    return $users; 
} 
0

尝试

public function points() 
    { 
     return $this->hasMany('Gamify\Point') 
      ->selectRaw('sum(points) as sum, user_id') 
      ->groupBy('user_id'); 
    } 

,并使用它像

 $data = User::with('points')->get(); 
+0

嗨@ nextt1,当我把这个代码Laravel说:“调用一个成员函数的OrderBy()的字符串”。严...... –

+0

试试这个新的代码。 – nextt1

+0

谢谢@ nextt1这是一个很好的起点,知道我会为了得到我想要的排名而玩(命令DESC和需要的列。 –