MySql JSON 架构

MySql JSON Schema

我在 MySql 中有一个 table 有点像这样:

create table json_docs (
  id int auto_increment primary_key,
  doc json not null
)

我还有一个 json 架构,该 doc 列遵循该架构。

{
  "$id": "https://my.org/namespace/doc.schema.json",
  "type": "object",
  "properties": {...}
}

有没有办法在插入或更新期间在 MySql 中强制执行该架构?

insert into json_docs (doc) values ('{...}')

我也在用PHPLaravel。如果Laravel的模型层有办法做到这一点,我也会感兴趣。

在此先感谢您的帮助!

MySQL 没有任何内置功能来根据架构验证 JSON 文档。

Update: This feature now exists in 8.0.17, but prior to that version, the following answer still applies:

您必须在您的应用程序中验证您的文档,独立于将其插入数据库。

请参阅 https://github.com/justinrainbow/json-schema,了解 PHP 中的开源 JSON 验证器。

MySQL 确实有 json 验证支持。

https://dev.mysql.com/doc/refman/8.0/en/json-validation-functions.html