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

BIT_COUNT not supported by phalcon?

Hey, I'm trying to find duplicate files by using following code, but I keep getting expection "Unknown expression type 94"

File::find([
                "BIT_COUNT (phash ^ ?0) < 4",
                "bind" => $file->phash
            ]);

Which leads to following trace { "function": "_getExpression", "class": "Phalcon\Mvc\Model\Query", "type": "->", "args": [ { "type": 94, "left": { "type": 355, "name": "phash" }, "right": { "type": 273, "value": "?0" } } ] },

If I can't use BIT_COUNT with phalcon ORM, is there some other way to accomplish same result, while keeping reslt as model format?



12.8k
Accepted
answer

You need to register custom function, example :

<?php
use Phalcon\Db\Dialect\MySQL as SqlDialect,
Phalcon\Db\Adapter\Pdo\Mysql;

$di->set('db', function () use ($config) {  
    $dialect = new SqlDialect();
    $dialect->registerCustomFunction('BIT_COUNT', function($dialect, $expression) {
            return sprintf(
                'BIT_COUNT(%d)',
                $dialect->getSqlExpression($expression['arguments'][0])
             );
        }
    ); 
    return new Mysql([
        'host' => $config[ENV]->database->host,
        'username' => $config[ENV]->database->username,
        'password' => $config[ENV]->database->password,
        'dbname' => $config[ENV]->database->dbname,
        'charset' => $config[ENV]->database->charset,
        'dialectClass' => $dialect
    ]);
});