Mysql 蛋糕3:JSON类型的列将NULL存储为字符串;空";
我的模型定义如下:Mysql 蛋糕3:JSON类型的列将NULL存储为字符串;空";,mysql,json,cakephp,cakephp-3.3,Mysql,Json,Cakephp,Cakephp 3.3,我的模型定义如下: <?php namespace App\Model\Table; use Cake\ORM\Table; use Cake\Database\Schema\Table as Schema; class AppLogsTable extends Table { protected function _initializeSchema(Schema $schema) { $schema->columnType('data', 'js
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Database\Schema\Table as Schema;
class AppLogsTable extends Table
{
protected function _initializeSchema(Schema $schema) {
$schema->columnType('data', 'json');
return $schema;
}
}
您必须使用一个自定义/扩展的数据库类型类来处理null
值,因此,内置的类将通过json\u encode()
传递所有内容
大致如下:
//src/Database/Type/NullAwareJsonType.php
名称空间App\Database\Type;
使用Cake\Database\Driver;
使用Cake\Database\Type\JsonType;
类NullAwareJsonType扩展了JsonType
{
数据库的公共函数($value,Driver$Driver)
{
如果($value==null){
返回null;
}
返回父::toDatabase($value,$driver);
}
}
然后,您可以覆盖内置的json
类型:
//config/bootstrap.php
\Cake\Database\Type::map('json',\App\Database\Type\NullAwareJsonType::class);
或者将其映射为新类型,并相应地设置列类型:
\Cake\Database\Type::map('nullAwareJson',\App\Database\Type\NullAwareJsonType::class);
$schema->columnType('data','nullAwareJson');
另见
在看到这一点(我自己也经历过几次)之后,我认为是时候将其插件化了:参见。