2014-08-30 55 views
0

我有一个有很多视频的回合桌。我的视频表与玩家之间有许多关系。在我的回合视图中,我展示了相关的视频,但我试图在回合视图中向视频的相关玩家展示。但我在这方面失败了。我发布了可以工作的代码,那就是我展示相关视频的回合视图。cakePHP - 多对多 - 访问玩家并在回合视图中显示他们

如何在回合视图中访问与视频相关的球员?这正在扰乱我一段时间!

发表:

round_id int(11)   
round_name varchar(45) 
tournament_id int(11) 

视频表:

video_id int(11) 
video_title varchar(45) 
video_date date 
video_scoreA 
video_scoreB 
video_url varchar(255) 
tournament_id int(11) 
round_id int(11) 

玩家表:

player_id int(11) 
player_firstname varchar(45) 
player_surname varchar(45) 
player_birthDate date 
player_turnedPro year(4) 
player_nickname varchar(45) 
player_nationality varchar(45) 
player_flag varchar(255) 
player_highestBreak varchar(45) 
player_highestRanking int(11) 
player_centuryBreaks int(11)s 
player_careerWinnings varchar(55) 
player_worldChampion varchar(45) 
player_image varchar(255) 
player_category varchar(45) 

players_videos表:

id int(11) 
video_id int(11) 
player_id int(11) 

Roundscontroller观点行动:

public function view($id = null) { 
    if (!$this->Round->exists($id)) { 
     throw new NotFoundException(__('Invalid round')); 
    } 
    $options = array('conditions' => array('Round.' . $this->Round->primaryKey => $id)); 
    $this->set('round', $this->Round->find('first', $options)); 
} 

大红大紫view.ctp:

<table cellpadding = "0" cellspacing = "0"> 
    <tr> 
     <th><?php echo __('Video Id'); ?></th> 
     <th><?php echo __('Video Title'); ?></th> 
     <th><?php echo __('Video Date'); ?></th> 
     <th><?php echo __('Video ScoreA'); ?></th> 
     <th><?php echo __('Video ScoreB'); ?></th> 
     <th><?php echo __('Video Url'); ?></th> 
     <th><?php echo __('Tournament Id'); ?></th> 
     <th><?php echo __('Round Id'); ?></th> 
     <th class="actions"><?php echo __('Actions'); ?></th> 
    </tr> 
    <?php foreach ($round['Video'] as $video): ?> 
     <tr> 
      <td><?php echo $video['video_id']; ?></td> 
      <td><?php echo $video['video_title']; ?></td> 
      <td><?php echo $video['video_date']; ?></td> 
      <td><?php echo $video['video_scoreA']; ?></td> 
      <td><?php echo $video['video_scoreB']; ?></td> 
      <td><?php echo $video['video_url']; ?></td> 
      <td><?php echo $video['tournament_id']; ?></td> 
      <td><?php echo $video['round_id']; ?></td> 
     </tr> 
    <?php endforeach; ?> 
</table> 

回答

0

的ContainableBehavior是你想要什么:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

所以去你的AppModel并添加public $actsAs = array('Containable');它。

在控制器方法中添加contain关键选项阵:

$options = array(
    'conditions' => array('Round.' . $this->Round->primaryKey => $id), 
    'contain' => array(
     'Video' => array('Player'), 
    ), 
) 

在你看来,你可以从第一视频一样访问的第一个球员名:

​​

或与foreach循环:

foreach ($round['Video'] as $video){ 
    echo $video['video_title']; 
    foreach ($video['Player'] as $player){ 
     echo $player['player_surname']; 
    } 
}