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

foreignKey with allowNulls true generate PDOException if wrong foreign key

I'm writing unit tests so I try to check various behaviours such as a wrong foreign key id.

Example : a personne has to have a project_id but not a status_id

in app/models/Person.php :

$this->belongsTo('project_id', 'Project', 'id', array(
    "alias" => "Project",
    "foreignKey" => array(
        "message" => "Project incorrect value"
    )
));
$this->belongsTo('status_id', 'Status', 'id', array(
    "alias" => "Status",
    "foreignKey" => array(
        "allowNulls" => true,
        "message" => "Status incorrect value"
    )
));

then in my unit test :

$person = new Person();
$person->assign([
    'project_id' => 3,  // doesn't exist in database
    'birth' => "1980-01-01",
]);
$personOk = $person->create();
var_dump((string)$personne->getMessages()[0]); // "Project incorrect value"

$person = new Person();
$person->assign([
    'project_id' => 1, // existing one
    'birth' => "1980-01-01",
    'status_id' => 10, // doesn't exist in database
]);
$personOk = $person->create();
var_dump((string)$personne->getMessages()[0]);

Here is the result :

There was 1 error:

1) Test\ModelUnitTest::testPersonCase
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db_unit`.`person`, CONSTRAINT `person_fk_4` FOREIGN KEY (`
statut_id`) REFERENCES `status` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

In my opinion, we should get a custom error message and not an exception.

Thanks

But if you remove allowNulls you got your message ?



2.0k

yes but then my first person created won't work as I need a status_id to be set