• php YII2空数组插入报错问题处理 Array to string conversion


    问题描述

    前端传空数组 [],php接收后处理不当插入数据库时报错Array to string conversion

    参数示例

    { "id": 0, //ID整型 "title": "标题", //字符串 "content": [] //数组 }

    模型验证规则

    • title: 必填/字符串
    • content: 非必填/字符串

    php代码

    public function add() { $data = Yii::$app->request->post();; if (!empty($data['content']) && is_array($data['content'])) { $data['content'] = json_encode($data['content']); } $model = new self(); $model->load($data, ''); if ($model->validate()) { return $model->save(); } else { jsonErrorReturn('fail', getFirstError($model->getErrors())); } }

    错误原因

    空数组[],php类型判定为array,但为空判定为true.导致没有被json_encode转义.在模型的validate方法中,又因为是空,没有被验证类型,导致最终以数组格式进行数据库insert报错

    var_dump(empty($data['content'])); //输出: bool(true) var_dump(is_array($data['content'])); //输出: bool(true)

    yii2框架模型验证validate方法

    public function validateAttributes($model, $attributes = null) { $attributes = $this->getValidationAttributes($attributes); foreach ($attributes as $attribute) { $skip = $this->skipOnError && $model->hasErrors($attribute) || $this->skipOnEmpty && $this->isEmpty($model->$attribute); if (!$skip) { if ($this->when === null || call_user_func($this->when, $model, $attribute)) { $this->validateAttribute($model, $attribute); } } } }

    因为$this->isEmpty($model->$attribute)判定为true,进行了跳过,所以没有验证

    解决方法

    1. 模型验证改为必填: required
    2. 针对前端传递的非必填数组类型参数,使用issetis_array进行判断是否需要json_encode

    __EOF__

    本文作者coding在路上
    本文链接https://www.cnblogs.com/zyilong/p/16575112.html
    关于博主:评论和私信会在第一时间回复。或者直接私信我。
    版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
    声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
  • 相关阅读:
    st语言【关键字】
    【Vue】Vue-Router 路由的理解和使用(2)
    Redis通用命令详解
    ansible - Role
    【模板】组合数取模
    自定义数字键盘(kotlin)
    电商数据API接口:新服务下电商网站、跨境电商独立站,移动APP的新型拉新武器
    【R语言数据科学】:文本挖掘(以特朗普推文数据为例)
    centos7安装mysql5.7笔记
    WebGIS系列(二):影像与切片
  • 原文地址:https://www.cnblogs.com/zyilong/p/16575112.html