lorem monkey
lorem monkey

Reputation: 3992

Reset to MySQL DEFAULT value on update in CakePHP

I am wondering how to reset a field to the DEFAULT value (the one set in MySQL structure) when performing an update action in CakePHP. Like using the DEFAULT keyword in SQL:

INSERT INTO items (position) VALUES (DEFAULT);

edit: I am not searching for a way to use the default on create, I am rather looking for a way to reset the field to it's default when it has been already used.

Upvotes: 1

Views: 534

Answers (2)

Arun Jain
Arun Jain

Reputation: 5464

You can simply unset the form input from the requested array, if you want to save its default value into the mysql database. You can try the following to achieve the same:

$item_details = $this->request->data;
unset($item_details['Item']['position']);
$this->Item->create();
$this->Item->save($item_details);

According to your edited question, if you want to reset any field during updating a record. you just need to use the MySql default() function.

$item_details = $this->request->data;
$this->Item->id = $item_details['Item']['id'];
$this->Item->saveField('position', DboSource::expression('DEFAULT(position)'));

Upvotes: 1

lorem monkey
lorem monkey

Reputation: 3992

To answer my own question, it could be done with:

$this->Item->saveField('position', DboSource::expression('DEFAULT(position)'));

or

$data['Item']['position'] = DboSource::expression('DEFAULT(position)');
$this->Item->save($data)

But - and here we go with the lost hours: to be able to use DboSource there had to be a database query before! Otherwise CakePHP throws the error Class 'DboSource' not found.

Upvotes: 0

Related Questions