我的模型定义如下:
<?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;
}
}
保存到数据库和检索数据时正确应用 JSON 格式。但是,如果我设置 $appLog->data = null
并通过 $this->appLogs->save($appLog)
保存它,它将保存一个字符串 null
而不是真正的 NULL 值。 app_logs
表中的 data
列设置为接受空值。
如果我取消注释列类型定义,它会正确存储空值。
如何从模型中保留自动 JSON 数据类型并正确存储 NULL?
最佳答案
您必须使用自定义/扩展数据库类型类来相应地处理 null
值,内置的将通过 json_encode()
传递所有内容,无论什么。
大致是这样的:
// src/Database/Type/NullAwareJsonType.php
namespace App\Database\Type;
use Cake\Database\Driver;
use Cake\Database\Type\JsonType;
class NullAwareJsonType extends JsonType
{
public function toDatabase($value, Driver $driver)
{
if ($value === null) {
return null;
}
return parent::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');
另见
关于mysql - 蛋糕 3 : column of type JSON stores a NULL as string "null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079398/