cakephp而不是user_id如何在视图

时间:2015-11-07 17:45:36

标签: mysql cakephp controller

我有3个表:用户,评论和视频。

在我的视频view.ctp中,我无法显示用户名,只显示user_id。

我无法弄明白,有人能指出我正确的方向吗?

用户模型:

public $hasMany = array(
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'user_id',
            'dependent' => false
        ),
}

视频模型:

public $hasMany = array(
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'video_id',
            'dependent' => false
        ),
}

评论模型:

public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        ),
        'Video' => array(
            'className' => 'Video',
            'foreignKey' => 'video_id'
        )
    );

}

视频view.ctp

<?php if (!empty($video['Comment'])): ?>
      <?php foreach ($video['Comment'] as $comment): ?>
         <p><?php echo $comment['comment_created']; ?></p>
         <p><?php echo $comment['User']['user_username']; ?></p>
         <p><?php echo $comment['user_id']; ?></p>
         <p><?php echo $comment['comment_body']; ?></p>
      <?php endforeach; ?>
<?php endif; ?>

VideosController

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

    $current_user = $this->Auth->user('user_id');

    if ($this->request->is('post')) {
        $this->Comment->create();
        /*save the current's user id in database*/
        $this->Comment->set('user_id', $current_user);
        /*save the current's video id in database*/
        $this->Comment->set('video_id', $id);
        if ($this->Comment->save($this->request->data)) {
            $this->Session->setFlash(__('You\'re comment has been placed.'));
            return $this->redirect(array('action' => 'view/' . $id));
        } else {
            $this->Session->setFlash(__('You\'re comment could not be placed. Please, try again.'));
        }
    }

    $this->set(compact('users', 'videos'));
}

1 个答案:

答案 0 :(得分:1)

<强>解决方案:

在控制器中:

$comments = $this->Video->Comment->find('all', array('conditions' => array('Comment.video_id' => $id)));

在视图中:

<?php foreach ($comments as $comment): ?>
    <p><?php echo $comment['User']['user_username']; ?></p>
    <p><?php echo $comment['Comment']['comment_created']; ?></p>
    <p><?php echo $comment['Comment']['comment_body']; ?></p>
<?php endforeach; ?>