Поле json
Поле json в Doctrine хранит данные в формате JSON. Оно позволяет сохранять массивы и объекты в одном столбце базы данных. При чтении данные автоматически преобразуются в PHP-массив или объект, а при записи - в JSON-строку.
Синтаксис
#[ORM\Column(type: 'json', nullable: true, options: ['jsonb' => true])]
Пример
Давайте создадим сущность с полем json и сохраним в него массив:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 255)]
private string $name;
#[ORM\Column(type: 'json', nullable: true)]
private ?array $attributes = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getAttributes(): ?array
{
return $this->attributes;
}
public function setAttributes(?array $attributes): self
{
$this->attributes = $attributes;
return $this;
}
}
?>
Пример
Давайте сохраним товар с массивом атрибутов в базу данных:
<?php
namespace App\Controller;
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ProductController extends AbstractController
{
#[Route('/product', name: 'product_create')]
public function create(EntityManagerInterface $entityManager): Response
{
$product = new Product();
$product->setName('hello');
$product->setAttributes([
'color' => 'abcde',
'size' => 'user',
'count' => 5,
]);
$entityManager->persist($product);
$entityManager->flush();
return new Response('saved');
}
}
?>
Результат выполнения кода:
"saved"
Пример
Давайте прочитаем сохранённые атрибуты:
<?php
namespace App\Controller;
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ProductController extends AbstractController
{
#[Route('/product/show/{id}', name: 'product_show')]
public function show(int $id, EntityManagerInterface $entityManager): Response
{
$product = $entityManager->getRepository(Product::class)->find($id);
$attributes = $product->getAttributes();
return new Response(json_encode($attributes));
}
}
?>
Результат выполнения кода:
{"color":"abcde","size":"user","count":5}
Смотрите также
-
поле
simple_array,
которое хранит простой массив в строке -
поле
string,
которое хранит короткие строки -
поле
text,
которое хранит длинные текстовые данные -
параметр
nullable,
который разрешает значение NULL