【问题标题】:Laravel One To Many relationship (Players and Team)Laravel 一对多关系(玩家和团队)
【发布时间】:2016-09-15 18:05:16
【问题描述】:

我正在尝试与我的表(玩家和团队)建立一些关系,但我无法在玩家关联中显示我的团队名称。

准则:一支球队有很多球员。外键 (TEA_ID) 在播放器表上。

这是我的团队模型 (Team.php)

class Team extends Model
{
protected $table = 'teams';
protected $primaryKey ='TEA_ID';

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

}

这是我的模板的一部分 (players.blade.php)

 <?php
        foreach($players as $player) {
    ?>
    <tr>
        <td><?php echo $player->PLA_ID?></td>
        <td><?php echo $player->PLA_Name?></td>
        <td><?php echo $player->PLA_Surname?></td>
        <td><?php echo $player->PLA_Pseudo?></td>
        @if($player->team)
            <td><?php echo $player->team->TEA_NAME?></td>
        @endif
        <td>|<span class="glyphicon glyphicon-pencil"></span>|</td>
        <td>|<span class="glyphicon glyphicon-trash" data-toggle="modal" data-target="#modalDelete"></span>|</td>
    </tr>

这是我的播放器控制器 (PlayerController.php)

public function show(){ // reçoit l'url http://monsite.fr/users avec le     verbe "get" et qui retourne le formulaire.

    $players = player::with('team')->get();
    return view('players', ['players' => $players]);

}

这是播放器模型 (Player.php)

class Player extends Model
{
protected $table = 'players';
protected $primaryKey ='PLA_ID';


public function team(){
    return $this->belongsTo('App\Models\Team');
}

}

比赛表正确显示数据,但不显示球队名称。我知道我可以使用 belongsTo() 方法,但我不知道我的错误在哪里。谢谢你的帮助,我会学到很多东西=)

【问题讨论】:

  • 你的播放器模型在哪里?
  • 对不起,这是模型,但我专门为这种关系制作了团队模型。
  • 你真的需要在你的玩家模型中设置belongTo() 关系。如果你想让$player-&gt;team-&gt;TEA_NAME 工作。
  • 请记住,如果您没有使用team_id 作为该关系中的外键,并且id 作为表中的默认主键,则需要在关系方法中手动设置键.查看文档laravel.com/docs/5.1/eloquent-relationships#one-to-many

标签: php laravel eloquent one-to-many


【解决方案1】:

您应该在 Player 模型中定义与 Team 的关系:

class Player extends Model
{
    protected $table = 'players';
    protected $primaryKey ='PLA_ID';

    public function team() {
        return $this->belongsTo('App\Model\Team');
    }

}

然后您将能够通过以下方式访问团队数据: (假设 $player 是 Player 模型的一个实例)

$player->team->TEA_NAME

希望对你有帮助。

【讨论】:

  • @Follio 也这么说,但它不起作用,但我正在阅读有关 One to May 的文档。
  • 你应该做一些调试。我不明白你为什么使用 player::with('team')->get();函数 show() 应该获取一个带有 Team ID 的参数,然后加载一个 Team 实例,以便将 $team->players 返回到视图。
猜你喜欢
  • 1970-01-01
  • 2015-07-29
  • 2019-06-26
  • 2018-09-27
  • 2016-08-08
  • 2021-04-30
  • 2018-06-16
  • 2021-11-02
  • 2013-07-26
相关资源
最近更新 更多