0

大家好,我正在使用 Cakephp 2.x,我需要为每个单独的事件输出个人用户的评论。每个用户都有许多事件和许多评论。我有事件、评论和用户模型,并希望允许用户在每个事件 view.ctp 上发布和查看评论。如果有人可以提供任何开始提示来实现此功能,将不胜感激。

我试图在事件 view.ctp 中输出评论模型索引表,但该表没有填充数据库中的评论,但评论 view.ctp 实际上用评论填充表。我使用了 $this->loadModel('Comments'); 事件控制器中的函数。

<div class="events view">
    <?php echo $this->Html->css('viewevent'); ?>
    <?php echo $this->element('maintitlegen'); ?>

    <div style="padding-top: 160px">
    <h2><?php  echo $event['Event']['name']; ?></h2>
    <dl>

        <dt><?php echo __('Event Image'); ?></dt>
        <dd>
            <?php echo $this->Html->image('/uploads/event/filename/thumb/small/'.$event['Event']['filename']); ?>
            &nbsp;
        </dd>


        <dt><?php echo __('Date'); ?></dt>
        <dd>
            <?php echo h($event['Event']['date']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Time'); ?></dt>
        <dd>
            <?php echo h($event['Event']['time']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Description'); ?></dt>
        <dd>
            <?php echo h($event['Event']['description']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Dresscode'); ?></dt>
        <dd>
            <?php echo h($event['Event']['dresscode']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Slogan'); ?></dt>
        <dd>
            <?php echo h($event['Event']['slogan']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Price'); ?></dt>
        <dd>
            <?php echo h($event['Event']['price']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Offers'); ?></dt>
        <dd>
            <?php echo h($event['Event']['offers']); ?>
            &nbsp;
        </dd>


    </dl>

    <!--<?php foreach ($users as $user): ?>
    <?php echo $user['Comment']['comment']; ?>
    <?php endforeach; ?>-->
    <!--<?php echo $ucomment['Comment']['comment']; ?>-->



    <?php echo $this->Form->create('Comment', array('controller' => 'comments', 'action' => 'add')); ?>
    <?php echo ('Add Comment'); ?>
    <?php echo $this->Form->input('comment'); ?>
    <?php echo $this->Form->end('Submit'); ?>

</div>
<div class="comments index">
    <h2><?php echo ('Comments'); ?></h2>
    <table cellpadding="0" cellspacing="0">
    <tr>
            <th><?php echo $this->Paginator->sort('id'); ?></th>
            <th><?php echo $this->Paginator->sort('comment'); ?></th>
            <th><?php echo $this->Paginator->sort('created'); ?></th>
            <th><?php echo $this->Paginator->sort('modified'); ?></th>
            <th><?php echo $this->Paginator->sort('user_id'); ?></th>
            <th><?php echo $this->Paginator->sort('event_id'); ?></th>
            <th class="actions"><?php echo __('Actions'); ?></th>
    </tr>
    <?php
    foreach ($comments as $comment): ?>
    <tr>
        <td><?php echo h($comment['Comment']['id']); ?>&nbsp;</td>
        <td><?php echo h($comment['Comment']['comment']); ?>&nbsp;</td>
        <td><?php echo h($comment['Comment']['created']); ?>&nbsp;</td>
        <td><?php echo h($comment['Comment']['modified']); ?>&nbsp;</td>
        <td>
            <?php echo $this->Html->link($comment['User']['name'], array('controller' => 'users', 'action' => 'view', $comment['User']['id'])); ?>
        </td>
        <td>
            <?php echo $this->Html->link($comment['Event']['name'], array('controller' => 'events', 'action' => 'view', $comment['Event']['id'])); ?>
        </td>
        <td class="actions">
            <?php echo $this->Html->link(__('View'), array('action' => 'view', $comment['Comment']['id'])); ?>
            <?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $comment['Comment']['id'])); ?>
            <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $comment['Comment']['id']), null, __('Are you sure you want to delete # %s?', $comment['Comment']['id'])); ?>
        </td>
    </tr>
<?php endforeach; ?>
    </table>
    <p>
    <?php
    echo $this->Paginator->counter(array(
    'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
    ));
    ?>  </p>

    <div class="paging">
    <?php
        echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
        echo $this->Paginator->numbers(array('separator' => ''));
        echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
    ?>
    </div>
</div>
</div>

///////////////////////////用户模型////////////// ///////////////////////////

<?php
class User extends AppModel {
    public $name = 'User';
    public $displayField = 'name';

    public $validate = array(
        'name'=>array(
            'Please enter your name.'=>array(
                'rule'=>'notEmpty',
                'message'=>'Please enter your name.'
            )
        ),
        'username'=>array(

            'That username has already been taken'=>array(
                'rule'=>'isUnique',
                'message'=>'That username has already been taken.'
            ),
            'Valid email'=>array(
                'rule'=>array('email'),
                'message'=>'Please enter a valid email address'
            )
        ),
        'email'=>array(
            'Valid email'=>array(
                'rule'=>array('email'),
                'message'=>'Please enter a valid email address'
            )
        ),
        'password'=>array(
            'Not empty'=>array(
                'rule'=>'notEmpty',
                'message'=>'Please enter your password'
            ),
            'Match passwords'=>array(
                'rule'=>'matchPasswords',
                'message'=>'Your passwords do not match'
            )
        ),
        'password_confirmation'=>array(
            'Not empty'=>array(
                'rule'=>'notEmpty',
                'message'=>'Please confirm your password'
            )
        )
    );

    public function matchPasswords($data) {
        if ($data['password'] == $this->data['User']['password_confirmation']) {
            return true;
        }
        $this->invalidate('password_confirmation', 'Your passwords do not match');
        return false;
    }

    public function beforeSave($options = array()) {
        if (isset($this->data['User']['password'])) {
            $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
        return true;
    }

    public $hasMany = array(
        'Event' => array(
            'className' => 'Event',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),

        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )

        );

        public $hasOne = array(
            'Profile' => array(
            'className' => 'Profile',
            'foreignKey' => 'user_id',
            'dependent' => true));

        var $actsAs = array(
        'MeioUpload.MeioUpload' => array('filename'=>array(
         'thumbsizes'=>array(
         'small'=>array(
         'width'=>'75',
         'height'=>'75',
         'forceAspectRatio'=>'C'
                        )))));


}
?>

///////////////////////////////用户控制器////////// //////////////////////

<?php
class UsersController extends AppController {

    public $name = 'Users';

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add');
    }

    public function isAuthorized($user) {
        if ($user['role'] == 'admin') {
            return true;
        }
        // if (in_array($this->action, array('delete'))) {
            // if ($user['id'] != $this->request->params['pass'][0]) {
                // return false;
            // }
        // }

        return true;
    }

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirect());   
            } else {
                $this->Session->setFlash('Your username/password combination was incorrect');
            }
        }
    }

    // public function logout() {
        // $this->redirect($this->Auth->logout());
    // }


    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->User->find('all'));
    }

    public function view($id = null) {
        $this->User->id = $id;

        if (!$this->User->exists()) {
            throw new NotFoundException('Invalid user');
        }

        if (!$id) {
            $this->Session->setFlash('Invalid user');
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read());
    }

    public function add() {
        if ($this->request->is('post')) {

            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('Now create your profile!');
                $this->Auth->login();
                $this->redirect(array('controller'=> 'profiles', 'action' => 'add'));
            } else {
                $this->Session->setFlash('Your account cannot be created. Please try again.');
            }
        }
        // if (!empty($user)){
                // $this->request->data['Profile']['user_id'] = $this->User->id;
                // $this->User->Profile->save($this->request->data);
            // }

    }

    public function edit($id = null) {
    $this->User->id = $id;
    $user = $this->User->read();

    if($user['User']['id'] != $this->Auth->user('id')){
        $this->redirect(array('controller' => 'events','action' => 'index'));
    }

    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }

    if ($this->request->is('get')) {
        $this->request->data = $user;
    } else {
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('Your account has been updated'));
            $this->redirect(array('controller' => 'events', 'action' => 'index'));
        } else {
           $this->Session->setFlash(__('Your account cannot be saved. Please try again.'));
        }
    }
}

    public function delete($id = null) {
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        if (!$id) {
            $this->Session->setFlash('Invalid id for user');
            $this->redirect(array('action'=>'index'));
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash('User deleted');
            $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash('User was not deleted');
        $this->redirect(array('action' => 'index'));
    }
}
?>
4

1 回答 1

0

我认为可以安全地假设您的评论表至少具有以下列:

  • ID
  • 用户身份
  • event_id
  • 评论(或名称)

您在 OP 中显示的视图是 events.view 方法的视图。但是您没有显示偶数模型或控制器。所以我不确定您是否需要事件控制器的帮助,或者您是否试图在用户控制器中显示事件数据。获取您在 OP 中显示的视图的所有评论的方法是从模型中提取所有评论,如下所示:

$this->set('comments', $this->Event->Comment->find('all', array('conditions' => array('event_id' => $event_id))));

如果您希望用户数据与其一起显示,则需要设置 recursive = 1 或编写一个连接来连接用户数据。

于 2013-01-16T04:10:26.020 回答