简体   繁体   中英

Mysql set default value to a json type column

I heard that mysql version prior to 8.0.13 accept default value for json type column, so I using the cmd:

ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT '{}' ;

but receive error:

Error Code: 1101. BLOB, TEXT, GEOMETRY or JSON column 'values' can't have a default value

So how do I fix it?

I'm using mysql version 8.0.19 and client tool Workbench

Thedocumentation 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.

You can make your default an expression by surrounding the litteral value with parentheses:

ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT ('{}') ;

Or:

ALTER TABLE templates CHANGE COLUMN values JSON NOT NULL DEFAULT (JSON_OBJECT()) ;

According to the laravel docs:

$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

https://laravel.com/docs/8.x/migrations#default-expressions

MySql syntax is a bit different than Oracle/Postgres, hence to make say JSON_Array as default, the query would be -

ALTER TABLE table_name ALTER column_name SET DEFAULT (JSON_ARRAY());

Further reference here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM