1

我的问题如下所示:

我想制作一个投票应用程序,人们可以在其中选择一个或多个事件(如涂鸦)。为此,我设置了一个名为 vote 的函数。在视图中,您可以使用复选框选择事件。模型是 Poll 和 Groupevent。民意调查有许多 Groupevents。我的问题是当我调用时updateAll(),相关 Groupevents 的所有值都会递增。

这是我的代码:

看法:

echo $this->Form->create('Poll', array('action' => 'vote'));

for($i=0; $i<$count; $i++){
    echo $this->Form->input('Groupevent.'.$i.'.votes', array('type'=>'checkbox', 
        'label'=>$this->Groupevent['startTime']));
    echo $this->Form->input('Groupevent.'.$i.'.id', array('type'=>'hidden'));
}   
echo $this->Form->input('id', array('type' => 'hidden'));   
echo $this->Form->end('vote');

控制器功能:

function vote($id=null){
    $this->Poll->id = $id;
    if ($this->request->is('get')) {
        $this->request->data = $this->Poll->read();
        $this->set('count', $this->Poll->Groupevent->find('count',
            array('conditions'=>array('Groupevent.poll_id'=>$this->Poll->id))));                                               
    } else {
        unset($this->Poll->Groupevent->validate['poll_id']);            
        if ($this->Poll->Groupevent->updateAll(
              array('Groupevent.votes'=>'Groupevent.votes+1'), 
              array('Groupevent.poll_id'=>$this->Poll->id))) 
        {                            
            $this->Session->setFlash('Your poll has been updated.');
            $this->redirect(array('action' => 'edit', $id));
        } else {
            $this->Session->setFlash('Unable to update your poll.');
        }
    }
}

我怎样才能使它工作,以便只增加检查的值?

提前致谢

编辑:

感谢您对阵列的建议。但我已经尝试了某些方法它不会工作。如何创建这个数组?

4

2 回答 2

4

看起来您正在updateAll对分配给选定投票的所有 Groupevents 运行查询:

if ($this->Poll->Groupevent->updateAll(
              array('Groupevent.votes'=>'Groupevent.votes+1'), 
              array('Groupevent.poll_id'=>$this->Poll->id))) 
        { 
...

您需要使用已检查 Groupevents 的 ID 创建一个数组,并添加一个条件,将更新限制为仅选定事件:

if ($this->Poll->Groupevent->updateAll(
              array('Groupevent.votes'=>'Groupevent.votes+1'),
              array('Groupevent.id IN' => $selectedEventsIds),
              array('Groupevent.poll_id'=>$this->Poll->id))) 
        {
...
于 2012-01-07T22:54:08.550 回答
0

我有一个正在开发的应用程序,允许用户(通过 jQuery)投票赞成或反对特定评论。这就是我实现它的方式。我基本上通过 Ajax/jQuery 调用这个函数,它只通过传递的参数增加评论;我的评论表有 2 个字段 - 喜欢和不喜欢。一个例子,如果 voteUp 和我也有很相似的 voteDown。

function voteUp($id = null){

    $this->autoRender = false; 
    if($this->RequestHandler->isAjax()){
        $this->Comment->id = $id;
        // Basically I get the value of liked(Field in Db) and increment it by 1
        $this->Comment->saveField('liked',$this->Comment->field('liked')+1);
    }       
    $newValue =  $this->Comment->findById($id);     
    //pass this value back to the view so it is displayed
    //using jQuery
    return $newValue['Comment']['liked'];
}

如果您还有问题,请告诉我

于 2012-01-08T19:06:06.667 回答