0

I have a organizers, which do tournaments where a player can participate.

So I have the tables organizer, tournament, participation, player.

I made a relation in the organizer model that gives me all players who ever payer in a tournament organized by that organizer.

    public function getTournaments()
    {
        return $this->hasMany(Tournament::className(), ['organizer' => 'id'])->where(['hasBeenAudited' => 1]);
    }

    public function getParticipations()
    {
        return $this->hasMany(Participation::className(), ['tournament' => 'id'])
            ->via('tournament')->where(['didShowUp' => 1]);
    }

    public function getPlayers() {
        return $this->hasMany(Player::className(), ['id' => 'player'])
            ->via('participation');
    }

So now I can do $model->players and retrieve all players that have ever played for that organization.

I now would like to order $model->players according to the number of tournaments a player has played for that organization, so that the player who has played the most tournaments for the organization will show up at the top.

How do I do that?

4

1 に答える 1

0

「グループ化」クエリを実行する必要があります。このようなことを試してください

$model->getPlayers()
  ->with('tournaments')
  ->select(['organization.name', 'player.name'])
  ->groupBy(['organization.name', 'player.name'])
  ->orderBy(['count(tournaments.id)'=>SORT_DESC])
  ->all();
于 2016-11-23T08:02:21.693 に答える