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.

What is the correct way to set default value for NOT NULL?

Hi, I have a mysql table with column 'sincelastscreenshot' NOT NULL DEFAULT '0'

I am getting an error, when trying to insert data ($screen->create()) without setting value for sincelastscreenshot field. SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'sincelastscreenshot' cannot be null

Does Phalcon understand the default values from MySQL table definition? What is the right way to set default values? using ORM?

Phalcon version 1.0



82.7k

You can pass a raw value telling the database to use the 'default' value:

<?php

use Phalcon\Db\RawValue;

$r = new Robots();
$r->name = 'Hello';
$r->type = new RawValue('default');
$r->create();

http://docs.phalconphp.com/en/latest/reference/models.html#skipping-columns

yes, but it is quite annoying to do it at every place where we need do insert/edit.

It is possible to set it inside the Model class?



82.7k
Accepted
answer

Yep, you can move that logic to your class:

<?php

use Phalcon\Mvc\Model,
    Phalcon\Db\RawValue;

class Robots extends Model
{
    public function beforeCreate()
    {
        if (!$this->type) { // use default value if the value is not set
            $this->type = new RawValue('default');
        }
    }
}

i think it should be

if (is_null($this->type)) { ... }

because you can set type to zero and the default to be something else ...



847
edited Nov '14

I think if the developer doesn't indicate the value of a field, the field should be default in SQL table definition rather than using NULL to replace it.
In most cases, developers want to the fields which are not indicated to be DEFAULT.

Yep, you can move that logic to your class:

```php <?php

use Phalcon\Mvc\Model, Phalcon\Db\RawValue;

class Robots extends Model { public function beforeCreate() { if (!$this->type) { // use default value if the value is not set $this->type = new RawValue('default'); } } } ```



1.4k

I have personally solved it by putting this in my base model:

public function beforeValidationOnCreate() {
    $metaData = $this->getModelsMetaData();
    $attributes = $metaData->getNotNullAttributes($this);

    // Set all not null fields to their default value.
    foreach($attributes as $field) {
        if(!isset($this->{$field}) || is_null($this->{$field})) {
            $this->{$field} = new RawValue('default');
        }
    }
}

The only thing I'm not sure about are the possible complications of setting fields like 'id' to the default, but it seems to work fine in my use case. This might also be slow if you don't cache metadata properly.

@Maurits Thanks for sharing that!

In PHP7:

$this->type ?? new RawValue('default');