竹林风 2020-04-10 18:01:43 1968次浏览 0条回复 0 0 0

长话短说 假设数据库有字段

a  int   11     不允许为null  默认值0
b  tinyint 1     不允许为null  默认值0
c  smallint 5     不允许为null  默认值0
d  varchar  255   不允许未null   默认值 empty string

假设表单提交数据为

[forn]=>[
    'a'=>1,'b'=>'','c'=>'12','d'=>''
]

按正常流程,在数据合法的情况下数据库该有一条a-b分别为 1 0 12 0的数据,但是实际上会报错提示某字段不能为null

在这里数据库的默认值就没效果了,取消不为null或模型增加default都可以解决,但是除非是长文本,我都不允许为null,第二种每次都要手动配置default规则也很麻烦,只要提交的数据不参与验证就行了,然后写了个方法过滤掉参数中字符串类型的空值数据,空的字符串类型数据其实也没啥用了吧

代码如下

/**
 * 删除数组空值
 * @param $arr
 * @return array
 * @author 竹林风@875384189 2020/4/9 18:41
 */
public static function removeEmptyAttr($arr, $newsArray = [])
{
    foreach ($arr as $index => $item) {
        if (is_array($item)) {//数组递归
            $newsArray[$index] = self::removeEmptyAttr($item);
        } else if (gettype($item) === 'string') {
            if (mb_strlen($item) === 0 || is_null($item)) {
                unset($item);
            } else {
                $newsArray[$index] = $item;
            }
        } else {
            $newsArray[$index] = $item;
        }
    }
    return $newsArray;
}

这样只要传入的数据内有string类型的数据,且数据长度为0,那么就去掉这个数据,但是还是希望官当在生成SQL时可以过滤掉nul 长度为0的字符串

    没有找到数据。
您需要登录后才可以回复。登录 | 立即注册