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

Saving boolean value in MySql

Hello, I've got a problem with saving boolean flags in MySql with Phalcon ORM.

For storing boolean values MySql uses a tinyint(1) field.

In Version 1.3.1 here https://github.com/phalcon/cphalcon/blob/1.3.1/ext/db/adapter/pdo/mysql.c#L221-L227 tinyint(1) columns were converted to boolean types automatically.

After this https://github.com/phalcon/cphalcon/issues/2236 bug report those lines were removed.

But there's the question: How can I use boolean types with MySql, PHP true/false constants and Phalcon ORM in my models?



51.2k

Why don't you cast ? Example of column name is_active:

public function getIsActive()
{
    return (bool) $this->is_active;
}


6.6k
edited Sep '14

Yes, I'm using the following code with casts now in my models. Actually I don't think it's a nice coding style but at least it's working...

<?php

use Phalcon\Mvc\Model as MvcModel;
class User extends MvcModel {
    protected $isAdmin;
    public function onConstruct() {
        $this->isAdmin = 0;
    }
    public function isAdmin() {
        return $this->isAdmin == 1 ? true : false;
    }
    public function setIsAdmin($isAdmin) {
        $this->isAdmin = (int) ((bool) $isAdmin);
        return $this;
    }
}