pll
pll

Reputation: 297

CakePHP updateAll() issues

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!

Upvotes: 10

Views: 23512

Answers (2)

mmv_sat
mmv_sat

Reputation: 456

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

}

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71918

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

Upvotes: 24

Related Questions