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

Implementation of Undo with SoftDelete

I have a base class all model classes derive from and it implements a SoftDelete behaviour this way:

$this->addBehavior(new \Phalcon\Mvc\Model\Behavior\SoftDelete(
            array(
                'field' => 'deleted_at',
                'value' => date('Y-m-d H:i:s')
            )
        ));

Now I need to implement an Undo feature and I have adde the following method to the Entry model:

/**
     * @access public
     * @static
     * @param number $id ID of the model record
     * @return mixed
     */
    public static function undelete($id)
    {
        $deletedField = 'deleted_at';

        $query = new \Phalcon\Mvc\Model\Query(
            "UPDATE Entry SET $deletedField = NULL WHERE id = :id:",
            \Phalcon\DI\FactoryDefault::getDefault()
        );
        $query->execute(array('id' => $id));
        return true;
    }

The code looks right to me. However, when I call the undelete() method from the controller I get the following exception phalcon exception



34.6k
Accepted
answer

Note that "Entry" is a model name, if it has a namespace you have to specify the full namespace, if you want to use plain SQL you have to use

$di = \Phalcon\DI\FactoryDefault::getDefault();
$di->getDb()->execute("UPDATE Entry SET $deletedField = NULL WHERE id = :id", array('id' => $id));

Adding the namespace fixed the problem