Laravel 4 - Sorting Data

折月煮酒 提交于 2019-12-11 16:10:12

问题


I am building a website in Laravel 4. I have a table in my DB called Games which contains a list of games. By default, I am sorting these Games with:

$games = Game::orderBy('title', 'ASC')->paginate(20);

Users can select which Games they are currently playing. These records are stored in a table called Players which stores game_id and user_id.

A couple of relevant models I have created:

class Game extends Eloquent {

    public function players()
    {
        return $this->hasMany('Player');
    }

}

class User extends Eloquent {

    public function players()
    {
        return $this->hasMany('Player');
    }

}

class Player extends Eloquent {

    public function game()
    {
        return $this->belongsTo('Game');
    }

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

}

What I would like to do is, be able to sort my Games by most popular (most total players) so that the Games list can be viewed in this way. I have tried the following, but it was nothing more than a stab in the dark as I'm pretty new to PHP frameworks and Laravel.

$games = Game::orderBy(count($this->players), 'DESC')->paginate(20);

Obviously the count($this->players) is wrong, but I'm kinda stuck on this one.

Thanks. Hopefully that all makes sense!

:)


回答1:


You need to JOIN the tables manually then SELECT COUNT(player.id), GROUP BY (game.id) and ORDER BY COUNT(player.id).

Your final query should look like this:

SELECT game.*, COUNT(player.id) AS players
FROM game
LEFT JOIN player
    ON player.game_id = game.id
GROUP BY player.id
ORDER BY players

Generating this with Laravel query builder is pretty simple:

DB::table('game')
    ->leftJoin('player', 'player.game_id', '=', 'game.id')
    ->groupBy('player.id')
    ->orderBy(DB::raw('COUNT(player.id)'))
    ->select('game.*')
    ->get();

Note that we cannot alias the COUNT to players and we cannot use models (no way to JOIN).



来源:https://stackoverflow.com/questions/19555259/laravel-4-sorting-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!