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

findBy and NULL values

Sorry if this has been asked before, but the search function appears to be broken, at least for me. I get only a blank page and a 500 Internal Server error from the server.

I have a MySQL table, controlling a workflow. The fields are mainly dates for when a specific part of the flow has been reached.

The fields could be like these:

task1ComplitionTime

task2ComplitionTime

When a field has the default value of "NULL" the step is pending.

What I need to do is to take all the rows with NULL in the field "task2ComplitionTime" but it seems that findBytask2CompletionTime has no way to searching for null. Is it not possible to use the findBy method when you are looking for null?

The code I am trying to make work is

$pendingTasks = workFlow::findByTask2ComplitionTime('NULL'); // Pure null and 'is null' has also been tried.
var_dump($pendingTasks->toArray()); // Only gives an empty array.

The following code works:

$pendingTasks = workFlow::find('task2ComplitionTime IS NULL');
var_dump($pendingTasks->toArray()); // Dumps the expected rows.

But I would really like to use the findBy if possible, as it looks nicer when reading the code.

findBy/findFirstBy uses an equals operator, but sql requires a condition like IS NULL which the finder does not provide, you can implement that method in your model or base model this way:

class Robots extends Model
{
    public static function __callStatic($method, $arguments = null)
    {
        $field = null;

        if (preg_match("/^findFirstNull/", $method)) {
            $type = "findFirst";
            $field = substr($method, 13);
        }

        /**
         * Check if the method starts with "find"
         */
        if ($field === null) {
            if (preg_match("/^findNull/", $method)) {
                $type = "find";
                $field = substr($method, 8);
            }
        }

        if (!$field) {
            return parent::__callStatic($method, $arguments);
        }

        return self::$type([
            "conditions" => strtolower($field) . " IS NULL"
        ]);
    }
}

Usage:

$robots = Robots::findNullName();
$robot = Robots::findFirstNullName();

Thank you. I'll try that. :)