Cakephp - 无法将布尔值更新为true?

时间:2013-06-24 02:22:36

标签: php mysql cakephp

这有效: ($ this->任务 - >保存('有效','0')

这不是: ($ this->任务 - >保存('有效','1')

它未通过模型验证: 模型 - >任务

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

TaskController.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:字段'active'是类型“tinyint”。

另外,Bake in 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

似乎绕过了验证,但没有更新数据库。

2 个答案:

答案 0 :(得分:1)

  

这有效:($ this-&gt; Task-&gt; save('active','0')

嗯,我对此表示怀疑:)

它可能不会出错,但它不会按预期执行。这将跳过验证并尝试将'active'作为数组进行处理。这样做的结果是它可能碰撞modified字段时间。

  

这不是:($ this-&gt; Task-&gt; save('active','1')

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

Model :: save(array $ data = null,boolean $ validate = true,array $ fieldList = array())]

请参阅the documentation,您的参数有误。您将字符串“active”作为数据传递,将boolean-ish值作为$validate的值传递。

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

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

或者这个:

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

或使用saveField:

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

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

答案 1 :(得分:0)

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

它清楚地表明你误用了save()。

您需要使用saveField()或updateAll()(atomic)来处理您的工作。