Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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;
$task->save();
$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;');
    $disableFk->execute();

    // update your userId now

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

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.



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

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

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


1.7k
Accepted
answer

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