Ошибка преобразования массива в строку при миграции - PullRequest
0 голосов
/ 24 июня 2019

В моем laravel 5.8 я установил поле json:

Schema :: create ('voice_categories', функция (таблица Blueprint $) { $ Table-> приращения ( '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 Ответ

2 голосов
/ 24 июня 2019

Вы пытаетесь вставить массив в тип данных столбца 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']),
]);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...