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

2,667次阅读

共计 1142 个字符,预计需要花费 3 分钟才能阅读完成。

在 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;
            }
        }
    }
}

正文完
 
Blood.Cold
版权声明:本站原创文章,由 Blood.Cold 2019-06-08发表,共计1142字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。