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

onValidationFails through related records

Hi all

Note: I'm using v2.0.13

I have a case where i use the method onValidationFails() in a model, which is created through a relation. So the conceptual case is:

<?php

class Robots extends Model

public function initialize()
    {
        $this->hasMany(
            "id",
            "RobotsParts",
            "robots_id"
        );
    }

<?php

class RobotsParts extends Model

public function initialize()
    $this->belongsTo(
                "robots_id",
                "Robots",
                "id"
            );
        }

public function validation()
{
    // Some validation
}

public function onValidationFails()
{
    $Setting = new SettingModel();
    $Setting->var = 'test';
    $Setting->update();
}

When I create a RobotsParts through Robots and the validation in RobotsParts fails, then onValidationFails is executed and the $Setting->update() returns TRUE! The problem is that $Setting->var is not updated in the database, it seems like that everything is rolled back. When I test create a RobotParts directly as RobotParts->create() then is $Setting->var updated in the database if validation fails.

Is this behavior expected and is there a way to establish a new transaction in the model which is not affected by the roolback.

Thanks in advance

edited Oct '16

Yes, this is happening because of transaction and it's expected. Why you can't just do:

if(!$robots->update()){
    $Setting = new SettingModel();
    $Setting->var = 'test';
    $Setting->create();
}

The problem is that there is several validations in RobotParts and the Settings table should only be updated if specific validations fails. I can control that in the RobotsParts model, but i think this is difficult in the suggeted solution. The settings table should neither be updated if the validation of Robots fails.