【发布时间】: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