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,进行了跳过,所以没有验证
解决方法
- 模型验证改为必填: required
- 针对前端传递的非必填数组类型参数,使用
isset
和is_array
进行判断是否需要json_encode