Laravel 5.6 withCount和where声明

时间:2018-04-16 19:51:55

标签: php mysql laravel where laravel-5.6

我正在使用laravel 5.6。

我有3个桌子:玩家,游戏和game_player表。

在PlayersController的索引操作中,检索每个玩家的游戏数量很容易:

//Get game count of every player
$players = Player::withCount('games')->get();

当玩家赢得游戏时,有没有办法检索游戏的游戏数量? (在玩家控制器的索引动作中)我不知道该怎么做。有人可以帮忙吗?

游戏桌迁移

$table->integer('winner')->unsigned()->index();
$table->foreign('winner')->references('id')->on('players')->onDelete('cascade');

enter image description here

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');

enter image description here

游戏模式关系

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');
}

playerscontroller

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);
}

我想要的结果是玩游戏(正在运行)并赢得比赛。

result

播放器>索引刀片

@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 using where clause on a withCount method),因为我也使用了多对多关系。

如果我使用的代码不正确,因为1需要是动态$ id:

$players = Player::withCount('games')
     ->having('winner', '=', 1)
     ->get();

我收到错误:

  

SQLSTATE [42S22]:未找到列:1054'having子句'中的未知列'获胜者'(SQL:选择players,(从{{1中选择计数())内部联接games位于game_playergames = idgame_player其中game_idplayers = {{1} {。id)来自game_player的{​​{1}} player_id = 1)

更新2

当我使用此代码时:

控制器

games_count

刀片索引

players

我得到了这个(不是我想要的,但我认为到达那里):

enter image description here

1 个答案:

答案 0 :(得分:2)

由于您在游戏桌上定义了一个外键,因此您已经在PlayerGame之间建立了一对多的关系。尝试将以下关系添加到Player模型中:

// Player.php
public function won()
{
    // must specify the foreign key because it is not the usual `_id` convention.
    return $this->hasMany(Game::class, 'winner');
}

然后在每个玩家上访问它,如:

@foreach($players as $player)
    {{ $player->won->count() }}
@endforeach

理想情况下,您应该在控制器中执行以下操作,而不是在视图文件中查询:

public function index()
{
    /*Load the view and pass the groups*/
    return \View::make('players.index')->with('players', Player::with('won')->get());
}