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

MVC model default values

There is support for @Column(..., default=value) and this is stored in the model meta data. This value is never used as a default value when creating objects with fields that have no value set.

I noticed that if the DBMS has a default column value, DEFAULT is used in the INSERT INTO table (...) VALUES (...) query. I would expect the annotated default value to be used, for the two reasons that a MVC model should hide DBMS logic and that the DBMS table can be out of sync with the MVC model. After all, the annotated default is stored in the model's meta data.

How can I construct a new object, using annotated defaults?

An example:

class User extends Model
{
    /**
     * @Identity
     * @Primary
     * @Column(type="integer", nullable=false)
     */
    private $ID;

    /**
     * @Column(type="string", length=32, default="John Doe")
     */
    private $name;
}

$user = new User();
$user->save(); // I expect $user to have $user->name set to 'John Doe', at least in the DBMS.
               // Instead it uses the default from the DMBS.


145.0k
Accepted
answer
edited Apr '16

Metadata annotations means that phalcon don't have to fetch database schema to build metadata. It doesn't mean it will use this default value in @Column you provide. If you do $user->save() it doesn't save with this value, this annotations are only information about your database schema. If you need to set some default value then use onConstruct or beforeSave method.

Thank your for your clarification. I presumed that @Column(..., default=value) would also apply to the initial values. Guess I am too familiar with Django, where this is the case.

Metadata annotations means that phalcon don't have to fetch database schema to build metadata. It doesn't mean it will use this default value in @Column you provide. If you do $user->save() it doesn't save with this value, this annotations are only information about your database schema. If you need to set some default value then use onConstruct or beforeSave method.

edited Apr '16

If you need such a hehaviour just use beforeSave event for example.