We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Model method not updating attribute, because of if statement...

I'm running Phalcon 1.3.3 on Windows (x64, VC9)

I've written mock code below that can explain better than I can with words.

Basically for some reason updating a model attribute (belongsTo()) that is within an if statement (for the same attribute), will not work.

save() returns true; there's no messages against the model, and the if statement code block is 10000% definitely executing.

Can anyone explain this? MySQL logging is showing that for some reason an Update query is executing against the status object itself, instead of Example object...

class Example extends \Phalcon\Mvc\Model
{
    public $id;

    public $status_id;

    public function initialize()
    {
            $this->belongsTo('status_id', '\Status', 'id', array('foreignKey' => true, 'alias' => 'status'));
    }

    public function accept1()
    {
        //Fetching this model relationship record is somehow not allowing me to update the status/status_id...
        //Update the $status_id var with the ID directly does not work either
        if($this->status->name === 'Pending'){
            $this->status = \Status::findFirst(['name = ?0', 'bind' => ['Accepted']]);
        }
    }

    public function accept2()
    {
        //This method works fine because of no if statement...
        $this->status = \Status::findFirst(['name = ?0', 'bind' => ['Accepted']]);
    }

}

/* EXAMPLE 1  - NOT WORKING */

$example1 = \Example::findFirst();    //id: 1, status: (Pending)
$example1->accept1();
$example1->save();

echo $example1->status->name."\n\n";   //Will be 'Accepted'   -  but DB not actually updated.
echo \Example::findFirst()->status->name."\n\n";   //Will be 'Pending' ...

/* EXAMPLE 2   -   WORKS  */

$example2 = \Example::findFirst();
$example2->accept2();
$example2->save();

echo \Example::findFirst()->status->name;   //WILL BE 'Active'... AS IT SHOULD

For now I'm just comparing $status_id; directly, so no relating object has to be fetched and I am able to update.



98.9k

It seems accept1 is not being called, only accept() and accept2()



1.5k

Phalcon is correct, in your code:

$example1 = \Example::findFirst();    //id: 1, status: (Pending)
$example1->accept(); // method does not exist !!!
$example1->save();

Best to check your webserver logs when you see strange things. Check the apache error_log. Don't know the location for windows

edited Oct '14

Sorry I should of clarified, this was mock code, a dumbed down version of the code I am actually using - this is not my actual code but it shows how to replicate the issue I am having.

I have fixed the typo, my question still remains :(