骑驴找蚂蚁

全干工程师

phalcon中模型NOT-NULL字段不能为NULL

在phalcon中model字段设置了not null在使用时候自动设置为空字符串或者0. 我们需要写一个监听方法beforeValidation框架底层会自动调用。

<?php
/**
 * Created by PhpStorm.
 * User: meshell
 * Date: 2018/7/18
 * Time: 16:51
 */

namespace App\Models;


use Phalcon\Db\Column;
use Phalcon\Db\RawValue;
use Phalcon\Mvc\Model\MetaData;

class Model extends \Phalcon\Mvc\Model
{
    /**
     * @return $this
     */
    public function beforeValidation()
    {
        /**
         * @var $metaData MetaData\Memory
         */
        $metaData = $this->getModelsMetaData();
        $field = $metaData->getDataTypes($this);
        /**
         * @var $notNullAttributes array
         */
        $notNullAttributes = $metaData->getNotNullAttributes($this);
        /**
         * @var $autoAttributes array
         */
        $autoAttributes = $metaData->getAutomaticCreateAttributes($this);
        /**
         * @var $primaryKey array
         */
        $primaryKey = $metaData->getPrimaryKeyAttributes($this);
        foreach ($field as $name => $type) {
            if (isset($this->$name) && $this->$name != null) {
                continue;
            }
            if (!in_array($name, $notNullAttributes)) {
                continue;
            }
            if (in_array($name, $autoAttributes) || in_array($name, $primaryKey)) {
                continue;
            }
            if ($type == Column::TYPE_INTEGER) {
                $this->$name = 0;
                continue;
            }
            if (in_array($type, [Column::TYPE_CHAR, Column::TYPE_VARCHAR, Column::TYPE_TEXT])) {
                $this->$name = new RawValue("");
            }
            if ($type == Column::TYPE_DATETIME) {
                $this->$name = CURRENT_TIME;
            }
        }
    }
}

留言