You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9执行Seeder时出现Array to string conversion错误

解决Laravel 9 Seeder中「Array to string conversion」错误

问题核心原因

你遇到的错误本质是:DataMaster模型未配置fieldDatas字段的JSON类型转换。虽然数据库迁移里定义了json('fieldDatas'),但Laravel Eloquent默认不会自动识别JSON字段,若模型未声明类型转换,直接存入数组时会触发数组转字符串的类型错误。你之前的同类型Seeder能正常运行,是因为对应模型已经配置了JSON字段的类型转换规则。

直接解决方案

修改App\Models\DataMaster模型,添加$casts属性指定fieldDatas的类型为array(Laravel会自动完成数组与JSON字符串的双向转换):

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class DataMaster extends Model
{
    // 允许批量赋值的字段(若未配置需补充)
    protected $fillable = ['formId', 'userId', 'kecamatanId', 'desaId', 'fieldDatas', 'level'];

    // 字段类型转换配置
    protected $casts = [
        'fieldDatas' => 'array',
    ];
}

额外验证与备选方案

  1. 检查批量赋值权限:确保$fillable数组包含fieldDatas,否则Eloquent会过滤该字段,可能引发其他异常。
  2. 手动序列化(不推荐):若暂时不想修改模型,可在Seeder中手动将数组转为JSON字符串:
DataMaster::create([
    'formId' => 1, 
    'userId' => 1, 
    'kecamatanId' => 1, 
    'desaId' => null, 
    'fieldDatas' => json_encode([['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']]), 
    'level' => 'kecamatan'
]);

优先推荐使用模型$casts配置,这是Laravel处理JSON字段的标准方式,能自动完成序列化/反序列化,避免手动编码的冗余操作。

内容的提问来源于stack exchange,提问作者ASHafizullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:25:28