Mysql 将默认值设置为 json 类型的列
Mysql set default value to a json type column
我听说 8.0.13 之前的 mysql 版本接受 json 类型列的默认值,所以我使用 cmd:
ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT '{}' ;
但收到错误:
Error Code: 1101. BLOB, TEXT, GEOMETRY or JSON column 'values' can't have a default value
那我该如何解决呢?
我正在使用 mysql 版本 8.0.19 和客户端工具 Workbench
从 8.0.13 版本开始,documentation says(重点是我的):
The BLOB
, TEXT
, GEOMETRY
, and JSON
data types can be assigned a default value only if the value is written as an expression, even if the expression value is a literal.
您可以通过用括号将文字值括起来使默认值成为表达式:
ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT ('{}') ;
或:
ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT (JSON_OBJECT()) ;
在 MySQL 的 8.0.13 版本之前,无法在 JSON 列上设置默认值,因为 8.0 文档指出 a few paragraphs later :
The BLOB
, TEXT
, GEOMETRY
, and JSON
data types cannot be assigned a default value.
MySql 语法与 Oracle/Postgres 有点不同,因此默认情况下说 JSON_Array,查询将是 -
ALTER TABLE table_name ALTER column_name SET DEFAULT (JSON_ARRAY());
进一步参考 here
根据 laravel 文档:
$table->json('movies')->default(new Expression('(JSON_ARRAY())'));
The default modifier accepts a value or an Illuminate\Database\Query\Expression instance. Using an Expression instance will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns
我听说 8.0.13 之前的 mysql 版本接受 json 类型列的默认值,所以我使用 cmd:
ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT '{}' ;
但收到错误:
Error Code: 1101. BLOB, TEXT, GEOMETRY or JSON column 'values' can't have a default value
那我该如何解决呢?
我正在使用 mysql 版本 8.0.19 和客户端工具 Workbench
从 8.0.13 版本开始,documentation says(重点是我的):
The
BLOB
,TEXT
,GEOMETRY
, andJSON
data types can be assigned a default value only if the value is written as an expression, even if the expression value is a literal.
您可以通过用括号将文字值括起来使默认值成为表达式:
ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT ('{}') ;
或:
ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT (JSON_OBJECT()) ;
在 MySQL 的 8.0.13 版本之前,无法在 JSON 列上设置默认值,因为 8.0 文档指出 a few paragraphs later :
The
BLOB
,TEXT
,GEOMETRY
, andJSON
data types cannot be assigned a default value.
MySql 语法与 Oracle/Postgres 有点不同,因此默认情况下说 JSON_Array,查询将是 -
ALTER TABLE table_name ALTER column_name SET DEFAULT (JSON_ARRAY());
进一步参考 here
根据 laravel 文档:
$table->json('movies')->default(new Expression('(JSON_ARRAY())'));
The default modifier accepts a value or an Illuminate\Database\Query\Expression instance. Using an Expression instance will prevent Laravel from wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns