Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP updateAll() issues

Tags:

cakephp

I have an images table with a column called type. I simply want to update all the rows to change the type to gallery where the user_id matches a particular user.

I am using this code

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

But I get this error: SQL Error: 1054: Unknown column 'gallery' in 'field list'

Why is gallery being added to the field list ?
Isn't the syntax supposed to set type to gallery?

Thanks!

like image 680
pll Avatar asked Aug 08 '11 20:08

pll


2 Answers

In your model do something like this in your method ....

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);

}

like image 77
mmv_sat Avatar answered Oct 31 '22 09:10

mmv_sat


Found this on the manual:

The $fields array accepts SQL expressions. Literal values should be quoted manually.

Thus, the following should work:

$this->Image->updateAll(
    array('Image.type' => "'gallery'"), 
    array('Image.user_id' => $this->Auth->user('id'))
);
like image 23
bfavaretto Avatar answered Oct 31 '22 07:10

bfavaretto