Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
Swader Avatar asked Apr 11 '13 14:04

Swader


3 Answers

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'));
    }
}
like image 190
twistedxtra Avatar answered Sep 21 '22 00:09

twistedxtra


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.

like image 29
mapsi Avatar answered Sep 20 '22 00:09

mapsi


Use Like below

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

public function initialize()
{
    $this->setSource('table_name');
    $this->skipAttributesOnCreate(['name_of_column']);
}
like image 28
Deji Kadri Avatar answered Sep 22 '22 00:09

Deji Kadri