How to force models to use default values ​​in Phalcon PHP Framework?

If the table has default values ​​for certain fields and NULL is not allowed, you can expect the script insert to use these default values, as MariaDB / MySQL usually does. For example, if the table products have an AI field "id", a required field "name" and two required fields "active" and "featured", which are equal to 1 by default, then the request

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

automatically inserts 1 as the value of the active and recognized. However, when using such Phalcon models:

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

returns validation errors that require "active" and "recognized".

Is there a flag that I must provide during model generation so that the Phalcon tools harvest and enter default values ​​in the model classes, or is there another way to force Phalcon to automatically use the default values ​​if they are found? I believe that a better approach would simply ignore fields that have not been set. Can I make these models?

+5
source share
3 answers

You can use a raw database value to avoid this in certain inserts:

<?php

use Phalcon\Db\RawValue;

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

Or, common before creating / updating 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 generated SQL INSERT:

use Phalcon\Db\RawValue;

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

, twistedxtra , Phalcon , , , , .

. .

+2

Use as below

The skipAttributesOnCreate function ensures that Phalcon does not attempt to put a value in this column. The database will apply the default value.

public function initialize()
{
    $this->setSource('table_name');
    $this->skipAttributesOnCreate(['name_of_column']);
}
0
source

All Articles