【问题标题】:Array to string conversion error in migration迁移中的数组到字符串转换错误
【发布时间】:2019-11-05 21:47:12
【问题描述】:

在我的 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 方法中使用,但看起来不是这样。

如何解决?

谢谢!

【问题讨论】:

    标签: laravel-5 migration


    【解决方案1】:

    您试图在 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']),
    ]);
    

    【讨论】:

      猜你喜欢
      • 2015-10-06
      • 1970-01-01
      • 2015-02-26
      • 2012-07-15
      • 2017-12-02
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      相关资源
      最近更新 更多