Swader Swader - 1 month ago 11
PHP Question

How to make models use defaults in Phalcon PHP Framework?

If a table has defaults on certain fields and NULL is not allowed, one would expect the insert script to use those defaults, as MariaDB/MySQL usually does. For example, if the table products has an AI field "id", a required field "name" and two required fields "active" and "featured" which both default to 1, then the query

INSERT INTO products (name) VALUES ('someName');


automatically inserts 1 as the value of active and featured. However, when using Phalcon's models like so:

$product = new Products();
$product->setName('someName');
$product->save();


returns validation errors saying "active" and "featured" are required.

Is there a flag I should provide during model generation in order for Phalcon tools to harvest and input the defaults into Model classes, or another way to make Phalcon automatically use defaults if found? Best approach would be just ignoring the fields that weren't set, I reckon. Can I make the models do that?

Answer

You can use a raw database value to avoid that, in specific inserts:

<?php

use Phalcon\Db\RawValue;

$product = new Products();
$product->setName('someName');
$product->setType(new RawValue('default')); //use default here
$product->save();

Or, general before create/update for specific fields:

use Phalcon\Db\RawValue;

class Products extends Phalcon\Mvc\Model
{
    public function beforeValidationOnCreate()
    {
        $this->type = new RawValue('default');
    }
}

Or ignore these fields in every SQL INSERT generated:

use Phalcon\Db\RawValue;

class Products extends Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributesOnCreate(array('type'));
    }
}
Comments