迁移中的数组到字符串转换错误

时间:2019-06-24 05:59:17

标签: laravel-5 migration

在我的laravel 5.8中,我设置了json字段:

Schema :: create('vote_categories',function(Blueprint $ table){     $ table-> increments('id');

$table->string('meta_description', 255)->nullable();
$table->json('meta_keywords')->nullable();


$table->timestamp('created_at')->useCurrent();

和种子中的一些初始化数据:

DB::table( 'vote_categories' )->insert([
    'id'                 => 1,
    'name'               => 'Classic literature',
    'slug'               => 'classic-literature',
    'active'             => true,
    'in_subscriptions'   => true,
    'meta_description'   => '',
    'meta_keywords'      => ['Classic literature'],
]);

和在模型中:

class VoteCategory extends MyAppModel
{

    protected $table      = 'vote_categories';
    protected $primaryKey = 'id';
    public $timestamps    = false;

    protected $casts = [
        'meta_keywords' => 'array'
    ];

但是运行迁移时出现错误:

$ php artisan migrate
Migration table created successfully.
...
Migrating: 2018_07_13_051201_create_vote_categories_table

   ErrorException  : Array to string conversion

  at /mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Support/Str.php:353
    349| 
    350|         $result = array_shift($segments);
    351| 
    352|         foreach ($segments as $segment) {
  > 353|             $result .= (array_shift($replace) ?? $search).$segment;
    354|         }
    355| 
    356|         return $result;
    357|     }

  Exception trace:

  1   Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Array to string conversion", "/mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Support/Str.php")
      /mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Support/Str.php:353

  2   Illuminate\Support\Str::replaceArray("?", [], "insert into `vt2_vote_categories` (`id`, `name`, `slug`, `active`, `in_subscriptions`, `meta_description`, `meta_keywords`) values (?, ?, ?, ?, ?, ?, ?)")
      /mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Database/QueryException.php:56

  Please use the argument -v to see more details.

为什么出错?我以为$ casts数组必须在-> insert方法中使用,但看起来不是这样。

如何修复?

谢谢!

1 个答案:

答案 0 :(得分:2)

您正尝试在JSON列数据类型中插入数组,因此会出现错误,请在插入前尝试在json中进行更改:

DB::table( 'vote_categories' )->insert([
    'id'                 => 1,
    'name'               => 'Classic literature',
    'slug'               => 'classic-literature',
    'active'             => true,
    'in_subscriptions'   => true,
    'meta_description'   => '',
    'meta_keywords'      => json_encode(['Classic literature']),
]);