api-platform.com - 使用学说将 JSON 数据存储到 TEXT mysql 列中
问题描述
我有一个具有 TEXT (MySQL) 属性的实体
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Index;
use ApiPlatform\Core\Annotation\ApiProperty;
/**
* @ApiResource(
* attributes={},
* collectionOperations={
* "get"={},
* "post"={
* "access_control"="is_granted('ROLE_COMPANY')"
* },
* },
* itemOperations={
* "get"={},
* "put"={"access_control"="is_granted('ROLE_COMPANY')"},
* }
* )
* @ORM\Entity(
* repositoryClass="App\Repository\SettingRepository",
* )
* @ORM\Table(
* indexes={@Index(name="domain_idx", columns={"domain"})}
* )
*/
class Setting
{
/**
* @var Uuid
* @ApiProperty(identifier=true)
* @ORM\Id
* @ORM\Column(type="string")
* @ORM\GeneratedValue(strategy="NONE")
*/
private $identifier;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $data = array();
/**
* @ORM\Column(type="string", nullable=true)
*/
private $domain = array();
public function getData()
{
if($this->data == null) return array();
$data = unserialize($this->data);
return $data;
}
public function setData($data): self
{
$this->data = serialize($data);
return $this;
}
/**
* @return mixed
*/
public function getIdentifier()
{
return $this->identifier;
}
/**
* @param mixed $key
*/
public function setIdentifier($identifier): self
{
$this->identifier = $identifier;
return $this;
}
/**
* @return mixed
*/
public function getDomain()
{
return $this->domain;
}
/**
* @param mixed $domain
*/
public function setDomain($domain): self
{
$this->domain = $domain;
return $this;
}
}
如果我尝试使用以下参数结构调用服务,它可以正常工作:
{
"data": "testData",
"identifier": "testIdentifier",
"domain": "domain1"
}
但是如果我想存储一个嵌入的 JSON 字符串,例如:"data": {"temp": 123}
我收到以下错误: hydra:description": "\"data\" 属性的类型必须是 \"string\", \"array\" given.",
我试图在 setData 方法中将对象转换为字符串。但是这个方法不会被调用。它接缝,API 平台检测到错误的类型并引发异常。
我发现了一些评论,有必要装饰属性: https ://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-adding-extra-data
谁能给我一个例子?这没用!序列化和反序列化属性数据的正确位置在哪里?
有人有想法吗?亲切的问候
解决方案
您需要json
在 MySQL 中将列类型设置为。它应该按预期运行。
/**
* @var array Additional data describing the setting.
* @ORM\Column(type="json", nullable=true)
*/
private $data = null;
我认为null
比空数组更一致,但这是您的选择。
推荐阅读
- react-native - React Native 延迟键盘出现在 android 上
- c# - 数据网格视图列名称更改
- azure-web-app-service - 如何将来自 Web 应用程序的所有出站呼叫设为私密
- c# - 在 Visual Studio Code for Mac 上找不到类型或命名空间名称“系统”
- jenkins - Jenkinsfile管道在指定目录中以循环模式运行命令
- c# - c#从数据表中求和相同间隔、日期和类型的值
- javascript - Javascript设置按钮激活
- django-rest-framework - DRF如何在没有queruset的情况下调用api
- android - Navigation.findNavController() 找不到视图
- python - 如何使用 Python 登录和爬取网站?