Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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?



10.6k
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
    ]);
});