Я использую ларавель 5.6.
У меня есть 3 таблицы: игроки, игры и таблица game_player.
Получить количество игр каждого игрока легко с помощью действия index PlayersController:
//Get game count of every player
$players = Player::withCount('games')->get();
Есть ли способ получить количество игр для игр, когда игрок выиграл игру? (в действии index контроллера игроков) я не знаю, как это сделать. Кто-нибудь может помочь?
перенос игровых столов
$table->integer('winner')->unsigned()->index();
$table->foreign('winner')->references('id')->on('players')->onDelete('cascade');
Миграция таблицы game_player
table->integer('game_id')->unsigned()->nullable();
$table->foreign('game_id')->references('id')->on('games')->onDelete('cascade');
$table->integer('player_id')->unsigned()->nullable();
$table->foreign('player_id')->references('id')->on('players')->onDelete('cascade');
связь модели игры
public function players(){
return $this->belongsToMany('App\Player')->withTimestamps();
}
//this is for the winner of the game
public function player()
{
return $this->hasOne('App\Player');
}
отношение модели игрока
public function games(){
return $this->belongsToMany('App\Game')->withTimestamps();
}
//the game the player has won
public function game()
{
return $this->belongsTo('App\Game');
}
контроллер игроков
public function index()
{
$players = Player::all();
//Get game count of every player
$players = Player::withCount('games')->get();
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', $players);
}
Результат, который я хочу, состоит в том, чтобы играть в игры (работает) и выигрывать игры.
игрок > указательный нож
@foreach($players as $player)
<p>{{ $player->id }}</p>
<p>{{ $player->firstname }} {{ $player->lastname }}</p>
<ul>
<li>Played games: {{ $player->games_count }}</li>
<li>Won games: </li>
</ul>
@endforeach
обновить
Я не думаю, что мы можем рассматривать это как дубликат этого вопроса (Laravel использует предложение where в методе withCount), потому что я также использую отношения «многие ко многим».
Если я использую этот код, который не является правильным, потому что 1 должен быть динамическим $id:
$players = Player::withCount('games')
->having('winner', '=', 1)
->get();
Я получаю сообщение об ошибке:
SQLSTATE[42S22]: Столбец не найден: 1054 Неизвестный столбец «победитель» в «содержащем предложении» (SQL: выберите
players
., (выберите количество () изgames
внутреннего соединенияgame_player
наgames
.id
=game_player
.game_id
гдеplayers
.id
=game_player
.player_id
) какgames_count
изplayers
сwinner
= 1)
обновление 2
Когда я использую этот код:
контроллер
$players = Player::all();
//Get game count of every player
$players = Player::withCount('games')->get();
$wongames = Player::withCount(['games' => function($query) { $query->where('winner', '=', 5); }])->get();
//$players = Player::withCount('games')->where('winner', '=', 1);
/*Load the view and pass the groups*/
return \View::make('players.index')->with('players', $players)->with('wongames', $wongames);
индекс лезвия
@foreach($players as $player)
<p>{{ $player->id }}</p>
<p>{{ $player->firstname }} {{ $player->lastname }}</p>
<ul>
<li>Played games: {{ $player->games_count }}</li>
@foreach($wongames as $wongame)
<li>Won games: {{ $wongame->games_count }}</li>
@endforeach
</ul>
@endforeach
Я получаю это (не то, что я точно хочу, но я думаю, что туда доберусь):
Player::withCount(['games' => function($query) { $query->where('winner', '=', 1); }]
. Логика та же, что и при использованииwith()
с дополнительными ограничениями запроса. - person Elias Soares   schedule 16.04.2018players
.*, (выберите количество (*) изgames
внутреннего соединенияgame_player
наgames
.id
=game_player
.game_id
гдеplayers
.id
=game_player
.player_id
) какgames_count
изplayers
гдеwinner
= 1) - person Gilko   schedule 16.04.2018->get()
. ты его включил? - person Elias Soares   schedule 16.04.2018