We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Cannot update values in database

Hi! I have a problem updating some values in database... I have the table Tasks and the table Users. Field userId in the table Tasks is foreign key to the table Users. When I try to update a value in this field nothing happens - value does not change:

$task = Tasks::findFirst('id=' . $taskId);
$task->userId = $newUserId;
$updatedTask = Tasks::findFirst('id=' . $task->id);
echo $updatedTask->userId; /*In this point I get old value*/

Then I tried to do it using modelsManager->createQuery() - in this case also nothing happened. Only when I used db->query() then values were updated.

Please explain to me why it happens and how I can address this problem.

edited Mar '14

Updating foreign key values usually doesn't work. Try this:

    $disableFk = new \Phalcon\MVC\Model\Query('SET foreign_key_checks = 0;');

    // update your userId now

    $enableFk = new \Phalcon\MVC\Model\Query('SET foreign_key_checks = 1;');

It is, ofcourse a better idea to use createQuery, but i just wanted to point you in the right direction.

Just as a sidenote, you don't need to specify "id =" when using findFirst(). Assuming you've set id as the table's primary key, this should work:

$task = Tasks::findFirst($taskId);

If the only argument to findFirst() is an integer, it assumes that integer should map to a primary key value.

$user = User::findFirstById($your_new_user_id);

$task = Tasks::findFirstById($taskId);
$task->user = $user;

// This should work without querying again
echo $task->getUserId();


Hi! I found the problem. Previous developer made compound primary key in the table Tasks - this key include the field userId. Therefore Phalcon didn't update this field. More if userId would be changed all fields couldn't be updated The problem is resolved - compound primary key