CakePHP updateAll()问题

时间:2011-08-08 20:31:12

标签: cakephp

我有一个图像表,其中包含一个名为type的列。我只想更新所有行,将类型更改为gallery,其中user_id与特定用户匹配。

我正在使用此代码

    $this->Image->updateAll(array('Image.type' => 'gallery'), 
    array('Image.user_id' => $this->Auth->user('id')));

但是我收到了这个错误:SQL Error: 1054: Unknown column 'gallery' in 'field list'

为什么要将图库添加到字段列表中?
是不是应该将类型设置为库的语法?

谢谢!

2 个答案:

答案 0 :(得分:24)

the manual上找到了这个:

  

$ fields数组接受SQL表达式。应手动引用文字值。

因此,以下内容应该有效:

$this->Image->updateAll(
    array('Image.type' => "'gallery'"), 
    array('Image.user_id' => $this->Auth->user('id'))
);

答案 1 :(得分:1)

在模型中,在您的方法中执行类似的操作....

public function saveImage($type='')
{
 // I would add a test for $type
 $db = $this->getDataSource();
 $fields = array('type' => $db->value($type, 'string')); // $db->value() will format strings needed for updateAll()
 $condition = array('user_id' => $this->Auth->user('id'));

 // I would add a test for user id before running updateAll()

  $this->updateAll($fields, $conditions);

}

相关问题