【问题标题】:Creating an index on a json column with Laravel使用 Laravel 在 json 列上创建索引
【发布时间】:2021-12-26 13:41:31
【问题描述】:

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

原来你只能在 json 列 when creating the table 上添加索引。

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

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

【问题讨论】:

  • 它到底在哪里说这只在创建表时才有效?
  • @Alex 执行create index area_groups_title_de on area_groups(JSON_VALUE(title, '$.de')); 之类的操作会给我一个 mysql 语法错误。
  • 而 json 索引上的 mysql 文档只提到了创建表
  • 您确定您使用的 mysql 版本支持您正在尝试执行的操作吗?另外,我认为您不需要在 DB::statement 中使用 DB::raw。
  • @IGP 是的,当我在控制台上手动运行 create table 语句时它可以工作。

标签: php mysql laravel eloquent mysql-8.0


【解决方案1】:

你可以使用json_encode(['id' =&gt; 1, 'name' =&gt; 'User 1']);

Laravel Schema 也支持 JSON 字段类型。

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

【讨论】:

  • 我正在寻找一种将 mysql 索引添加到我的 json 列中的列的方法,而不是一种编码 json 的方法。
猜你喜欢
  • 2018-10-01
  • 1970-01-01
  • 2014-08-21
  • 2011-07-01
  • 2016-11-18
  • 2011-05-23
  • 2018-10-28
  • 2019-02-27
  • 1970-01-01
相关资源
最近更新 更多