首页 > 解决方案 > 使用 Laravel 在 json 列上创建索引

问题描述

我有一个带有一JSON列的数据库表。我现在想为该 json 的部分添加索引。

事实证明,您只能在创建表时在 json 列上添加索引。

这是我在迁移中尝试过的:

DB::statement(DB::raw(<<<SQL
CREATE TABLE area_groups (
  title JSON, 
  `created_at` timestamp null, 
  `updated_at` timestamp null, 
  INDEX area_groups_title_de (
    (
      JSON_VALUE(title, '$.de')
    )
  ), 
  INDEX area_groups_title_en (
    (
      JSON_VALUE(title, '$.en')
    )
  )
) default character set utf8mb4 collate 'utf8mb4_unicode_ci'
SQL
));

Schema::table('area_groups', function (Blueprint $table) {
    $table->id()->change();
    $table->foreignId('area_id')->change()->constrained();
});

我的想法是在原始 db 语句中创建 json 列和索引,然后使用 Laravel 的迁移助手完成其余的工作。

创建表似乎可行,但运行此迁移失败并显示以下错误消息:

Argument 1 passed to Doctrine\DBAL\Schema\Index::_addColumn() must be of the type string, null given, called in vendor/doctrine/dbal/src/Schema/Index.php on line 72

标签: phpmysqllaraveleloquentmysql-8.0

解决方案


您可以使用json_encode(['id' => 1, 'name' => 'User 1']);

Laravel Schema也支持 JSON 字段类型。

您也可以使用文本字段类型来存储 JSON 数据。


推荐阅读