Laravel 4多对多关系不显示相关数据

时间:2013-05-12 20:09:51

标签: many-to-many laravel pivot-table laravel-4 eloquent

我正在使用以下模型:玩家扩展用户的游戏,用户和播放器。在这种情况下,游戏和玩家的关系为N:N,用户扩展为Confide。所以代码就像:

应用/模型/ Game.php

<?php

class Game extends Eloquent {

    protected $guarded = array();
    protected $table = 'users';
    public $timestamps = false;

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

应用/模型/ user.php的

<?php

use Zizaco\Confide\ConfideUser;

class User extends ConfideUser {
    protected $table = 'users';
    public $timestamps = false;
    protected $hidden = array('password');

    //Here go original Confide functions
}

应用/模型/ Player.php

<?php

class Player extends User{
    public function games(){
        return $this->belongsToMany('Game');
    }
}

我填充了名为game_player的数据透视表。当玩家扩展用户时,数据透视表就像这样:

game_player

id
game_id
user_id

但是,如果我运行这个超级简单的例子,我有一个错误:

$game = Game::find($gameId);
$player = $game->players();  //Error in this line

错误

Call to undefined method Illuminate\Database\Query\Builder::players()

我很困惑,因为我没有error about pivot table was not found,所以我觉得关系很好。

另一方面,如果我获得var_dump games var:

的var_dump($游戏)

object(Game)[181]
  protected 'table' => string 'games' (length=5)

  //more var info about DB

  protected 'relations' => 
    array (size=0)
      empty
  protected 'hidden' => 
    array (size=0)
      empty
  protected 'visible' => 
    array (size=0)
      empty
  protected 'guarded' =>

如果关系被创建得很好......关系var是否应该有任何数据?

谢谢!

1 个答案:

答案 0 :(得分:0)

指出可以解决问题的事情:

  1. 您的Game.php表名错误。

  2. 获得玩家后,该行应为:

    $ game = Game :: with('players') - &gt; find($ gameId); $ player = $ game-&gt;玩家;