Laravel 9.6填充JSON字段时类型转换报错,如何解决?
Laravel 9.6 Seeder填充JSON字段报错修复方案
问题原因
你使用的ProductCategory::insert()属于查询构造器层面的批量插入操作,不会触发模型的$casts类型转换逻辑。尽管你在模型中配置了properties字段转为数组,但insert()会直接将原始数组传递给数据库,而数据库的JSON字段需要JSON格式的字符串,因此触发了「数组转字符串」的错误。
修复方案
方案一:使用模型create()方法(推荐)
create()方法会经过模型的属性处理流程,自动将数组转为符合要求的JSON字符串:
$properties = $faker->randomElements(['aB','bc','cD','ac','HD'], 2); ProductCategory::create([ 'product_id' => $nextProduct->id, 'category_id' => $nextCategory->id, 'properties' => $properties, ]);
注意:需要在ProductCategory模型中添加批量赋值白名单,否则会触发批量赋值错误:
class ProductCategory extends Model { // ... 其他代码 protected $fillable = ['product_id', 'category_id', 'properties']; }
方案二:手动转换数组为JSON字符串(适合批量插入场景)
如果需要批量插入多条数据,可以手动用json_encode()处理properties字段:
$properties = $faker->randomElements(['aB','bc','cD','ac','HD'], 2); ProductCategory::insert([ 'product_id' => $nextProduct->id, 'category_id' => $nextCategory->id, 'properties' => json_encode($properties), ]);
方案三:使用模型save()方法
先实例化模型,赋值属性后保存,同样会触发类型转换:
$properties = $faker->randomElements(['aB','bc','cD','ac','HD'], 2); $productCategory = new ProductCategory(); $productCategory->product_id = $nextProduct->id; $productCategory->category_id = $nextCategory->id; $productCategory->properties = $properties; $productCategory->save();
内容的提问来源于stack exchange,提问作者mstdmstd
相关产品推荐
相关产品推荐

