将 JSON 数据存储到 TEXT mysql 列中

Store JSON data into TEXT mysql column with doctrine

我有一个具有一个 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": "The type of the \"data\" 属性必须 \"string\", \"array\" 给定。",

我试图在setData 方法中将对象转换为字符串。但是这个方法不会被调用。它接缝,API-平台检测到错误的类型并抛出异常。

我发现了一些评论,认为有必要装饰属性: https://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-adding-extra-data

有谁能举个例子吗?这是行不通的! 序列化和反序列化 属性 数据的正确位置在哪里?

有人有想法吗? 亲切的问候

您需要在 MySQL 中将列类型设置为 json。它应该按预期运行。

/**
 * @var array Additional data describing the setting. 
 * @ORM\Column(type="json", nullable=true)
 */
    private $data = null;

我认为 null 比空数组更一致,但这是你的选择。