php - 使用 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
解决方案
您可以使用json_encode(['id' => 1, 'name' => 'User 1']);
Laravel Schema也支持 JSON 字段类型。
您也可以使用文本字段类型来存储 JSON 数据。
推荐阅读
- java - 多个线程从 ConcurrentLinkedQueue 读取,并进入 DB。并非所有条目都在写入
- javascript - 使用 Select2 和其他表单控制元素或 input-group-btn 响应式修复输入组
- javascript - 函数和变量提升的意外结果
- maven - Travis CI 没有为 Maven Surefire 插件链接库
- c# - 在 DataGridView 控件中展开/折叠行
- c# - C# 为标签获取良好的颜色
- c++ - 从头文件传递 cpp 选项
- javascript - 标签中的双重事件
- java - 具有多个或运算符的 Jpa 存储库 findBy 方法签名?
- css - Bootstrap 4 网格格式