Laravel执行数据库Seeder报Array to string conversion错误
报错原因
执行php artisan migrate --seed触发Array to string conversion错误,核心是给track_id字段传入了数组值,但数据库字段默认无法直接存储数组类型,写入时PHP尝试把数组强转为字符串失败。
对应Seeder代码片段:
[ 'id' => 1, 'album_title' => '2022', 'featured_image' => 'index_1656159760.jpg', 'featured_image_url' => 'http://127.0.0.1:8000/storage/artists/albums/featured_image/index_1656159760.jpg', 'genre_id' => 4, 'track_id' => ["1","2"], 'album_type_id' => 2, 'language_id' => 3, 'description' => 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem.', 'artist_id' => 1, ],
解决方法
根据实际的字段设计选对应方案即可:
- 方案1:字段设计为存储JSON格式数组
先把数据库中track_id字段类型修改为json(或longText),之后在对应Album模型中添加类型转换配置,框架会自动完成数组和JSON字符串的互转:
配置完成后Seeder中直接传数组写入即可,不会再触发类型转换错误,后续从数据库读取该字段时也会自动转回数组类型,不需要手动处理。// 在Album模型中添加 protected $casts = [ 'track_id' => 'array', ]; - 方案2:专辑和曲目为多对多关联关系
这种场景下不应该在专辑表存track_id数组,不符合数据库设计规范。你需要新建专辑和曲目的多对多关联中间表(命名一般为album_track),Seeder中分开写入数据再做关联:// 先创建专辑数据 $album = Album::create([ 'id' => 1, 'album_title' => '2022', 'featured_image' => 'index_1656159760.jpg', 'featured_image_url' => 'http://127.0.0.1:8000/storage/artists/albums/featured_image/index_1656159760.jpg', 'genre_id' => 4, 'album_type_id' => 2, 'language_id' => 3, 'description' => 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem.', 'artist_id' => 1, ]); // 关联对应曲目ID $album->tracks()->attach([1, 2]); - 方案3:临时用字符串拼接存储(不推荐)
如果只是临时测试需要快速解决,可以手动把数组转成逗号分隔的字符串写入:
这种方式后续做数据查询、关联维护的成本极高,正式项目不要使用。'track_id' => implode(',', ["1","2"]),
内容的提问来源于stack exchange,提问作者vijay
相关产品推荐
相关产品推荐

