cakeHP多对多关系-在视图中加载与关系无关的表记录


cakePHP Many to Many relationship - load table records inside view that has nothing to do with the relation

我有一个版本、视频表。一个版本可以有许多视频。

一个视频有很多播放器,一个播放器有很多视频。因此,视频和玩家之间存在着多对多的关系。

在我的版本视图中,我加载了与该版本相关的所有视频。但我也想加载属于视频的玩家信息。在数据库中,版本和播放器之间没有关系,因为这种关系是视频和播放器之间的关系(多对多-播放器_视频)。

我可以加载与视频相关的players_id。我把那些id从播放者视频表里拿出来。

如何在版本视图中加载属于视频的玩家信息?

版本模型有很多关系:

public $hasMany = array(
    'Video' => array(
        'className' => 'Video',
        'foreignKey' => 'edition_id',
        'dependent' => false,
    )
);

EditionsController视图操作:

public function view($id = null) {
    if (!$this->Edition->exists($id)) {
        throw new NotFoundException(__('Invalid edition'));
    }
    $options = array('conditions' => array('Edition.' . $this->Edition->primaryKey => $id));
    $this->set('edition', $this->Edition->find('first', $options));
    $tab = array('Video.' . $this->Video->primaryKey => $id); // which you loop for the video list and fill with their ids
    $playersvideos = $this->Edition->Video->PlayersVideo->find('all', array('conditions' => array('PlayersVideo.video_id' => $tab),'recursive'=>2));
    $this->set('playersvideos ', $playersvideos);
}

view.ctp:

<?php foreach ($edition['Video'] as $video): ?>
    <tr>
        <td><?php echo $video['video_id']; ?></td>
        <td><?php echo $video['video_title']; ?></td>
        <td>...</td>
        <td>
            <?php foreach ($playersvideos as $playervideo): ?>
                    <?php echo $playervideo['PlayersVideo']['player_id']; ?>
                    <?php echo $playervideo['PlayersVideo']['video_id']; ?>
            <?php endforeach; ?>
        </td>
    </tr>
<?php endforeach; ?>

玩家拥有并属于许多关系:

public $hasAndBelongsToMany = array(
    'Video' => array(
        'className' => 'Video',
        'joinTable' => 'players_videos',
        'foreignKey' => 'player_id',
        'associationForeignKey' => 'video_id',
        'unique' => 'keepExisting',
    )
);

视频具有并属于许多关系:

public $hasAndBelongsToMany = array(
    'Player' => array(
        'className' => 'Player',
        'joinTable' => 'players_videos',
        'foreignKey' => 'video_id',
        'associationForeignKey' => 'player_id',
        'unique' => 'keepExisting',
    )
);

PlayersVideo属于关系

public $belongsTo = array(
    'Video' => array(
        'className' => 'Video',
        'foreignKey' => 'video_id',
    ),
    'Player' => array(
        'className' => 'Player',
        'foreignKey' => 'player_id',
    )
);

好的,下面是我的操作方法:在控制器中,例如在功能编辑中:

public function edit($id = null){
....
$tab = array(); // which you loop for the video list and fill with their ids
$players= $this->Edition->Video->Player->find('all',array(
                                'conditions' => array('Player.video_id IN ' => $tab),'recursive'=>2));
$this->set('player',$players);
}

在您的edit.ctp中,您可以循环查找它并根据需要显示它。希望它能帮助