0

这有效: ($this->Task->save('active', '0')

这不会: ($this->Task->save('active', '1')

模型验证失败:模型->任务

'active' => array(
    'boolean' => array(
    'rule' => array('boolean'),
    ),
),

任务控制器.php

这有效:

public function deactivate ($id = null) {
    $this->Task->id = $id;
    if (!$this->Task->exists()) {
        throw new NotFoundException(__('Invalid task'));
    }
    $this->request->onlyAllow('post');
    if ($this->Task->save('active', '0')) {
        $this->Session->setFlash(__('The task has been saved'));
        $this->redirect($this->referer());
    } else {
        $this->Session->setFlash(__('The task could not be saved. Please, try again.'));
        }

这不会:

public function activate ($id = null) {  
    $this->Task->id = $id;  
    if (!$this->Task->exists()) {  
        throw new NotFoundException(__('Invalid task'));  
    }    
    $this->request->onlyAllow('post');    
    if ($this->Task->save('active', 1)) {  
    $this->Session->setFlash(__('The task has been saved'));  
    $this->redirect($this->referer());  
   } else {  
    $this->Session->setFlash(__('The task could not be saved. Please, try again.'));  
    $this->redirect($this->referer());  
   }  
} 

这是来自 View/Tasks/index.ctp 的调用:

<?php 
     if ($task['Task']['active'] == 1){
        echo $this->Form->postLink(__('Deactivate'), array('action' => 'deactivate', $task['Task']['id']),null, __('Are you sure you want to return # %s to the project?', $task['Task']['id']));
    } else {
        echo $this->Form->postLink(__('Activate'), array('action' => 'activate', $task['Task']['id']),null, __('Are you sure you want to send # %s to your todo list?', $task['Task']['id']));
    }
  ?>

mysql db:字段“活动”是类型“tinyint”。

此外,由 Bake 在 Views/Tasks/edit.ctp 中生成的复选框表单控件也可以正常工作。

我还尝试了以下方法:

 ($this->Task->save('active', 1)
 ($this->Task->save('active', true)
 ($this->Task->save('active', 'true')
 ($this->Task->save('active', '2')

这个:

 ($this->Task->save('active', `1`) //notice the tic marks

似乎绕过验证,但不更新数据库。

4

2 回答 2

1

这有效: ($this->Task->save('active', '0')

好吧,我对此表示怀疑:)

它可能不会给出错误,但不会像您期望的那样。这将跳过验证并尝试'active'作为数组处理。这样做的结果可能只是增加了modified现场时间。

这不会: ($this->Task->save('active', '1')

这取决于您的验证规则,但无论如何语法都不会达到您的预期。

模型::保存(数组 $data = null,布尔 $validate = true,数组 $fieldList = array())]

请参阅文档,您的参数错误。您将字符串“active”作为您的数据传递,并将您的布尔值作为$validate.

这会起作用(或者,不会因为语法错误而失败):

$this->Task->save(array('active' => $value));

或这个:

$this->Task->save(array('Task' => array('active' => $value)));

或使用 saveField:

$this->Task->saveField('active', $value)

如果有疑问 -使用 bake,或与它生成的代码进行比较。

于 2013-06-24T10:01:32.123 回答
0

你为什么不只是按照文档? http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false

它清楚地表明您在滥用 save()。

您需要使用 saveField() 或 updateAll() (原子)来完成您正在做的事情。

于 2013-06-24T07:56:42.570 回答