简体   繁体   中英

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?

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'));
    }
}

Although I find twistedxtra's answer fascinating from the aspect that Phalcon contains this wicked method to read the column default, I believe from a architectural point of view this might be the wrong approach as you rely on your database to define the defaults of the properties of your model.

I would set the default value when declaring the property and keep the logic in the application layer. But that's just me.

Use Like below

The skipAttributesOnCreate will make sure Phalcon does not attempt to put aa value in that column. The database will apply the default value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM