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

时间:2014-08-29 14:14:21

标签: php cakephp many-to-many cakephp-appmodel

我有一个版本,视频表。一个版本可以有很多视频。

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

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

我可以加载与视频相关的players_id。我从player_videos表中得到了那些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',
    )
);

1 个答案:

答案 0 :(得分:1)

好的,我在这里怎么做: 在控制器中,例如在函数编辑中:

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中,您循环播放并按需要显示它。它有帮助