2016-09-15 4 views
1

テーブル(プレイヤーとチーム)との関係を作ろうとしていますが、チームの名前をプレイヤーのアソシエイトに表示できません。Laravel One To Manyの関係(プレイヤーとチーム)

ガイドライン:チームには多くのプレーヤーがいます。外部キー(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

ここで

0は

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


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

} 

表が正しく表示件のデータをplayesプレーヤーモデル(Player.php)ではなく、チームの名前。私はbelongsTo()メソッドを使うことができますが、どこにエラーがあるのか​​分かりません。あなたのプレイヤーモデルのチームとの関係を定義する必要があります

+0

あなたのプレーヤーモデルはどこですか? – follio

+0

すみません、ここはモデルですが、私は関係のためにチームモデルで特別に仕事をしました。 –

+0

あなたは本当にあなたのPlayer Modelで 'belongsTo()'関係を設定する必要があります。あなたが '$ player-> team-> TEA_NAME'を働かせたいならば。 – follio

答えて

0

)=私は多くのことを学びます、あなたの助けをありがとう:

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

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

} 

その後、あなたは、このようにチームのデータにアクセスできるようになります: (と仮定すると、$プレーヤーがプレーヤーモデルのインスタンスである)

$player->team->TEA_NAME 

は、それが役立つことを願って。

+0

@ Folioは同じことだが動作しませんが、私は1〜5月についてのドキュメントを読んでいます。 –

+0

いくつかのデバッグを行うべきです。私はなぜplayer ::を( 'team') - > get();と使うのか分かりません。関数show()はチームIDでパラメータを取得し、Teamのインスタンスをロードするので、$ team-> playersをビューに戻すことができます。 – xyzale