Vinstrok
@Vinstrok
Веб разработчик

Как десериализовать массив json-ов c отношением OneToMany?

Здравствуйте, накидал код такого плана, на выходе получаю два объекта Users все как положено но без вложенного объекта ipContract, вопрос умеет ли symfony десериализовать массив джосонов таким образом чтобы в ipContract который связан с User отношением OneToMany так же создавался объект с данными

$normalizer = [
            new ObjectNormalizer(),
            new ArrayDenormalizer()
        ];

        $encoders = [
            'json' => new JsonEncoder()
        ];

        $serializer = new Serializer($normalizer, $encoders);
        $jsonUser = [
            [
                'lastName' => 'Алексей',
                'firstName' => 'Виноградов',
                'fullName' => 'Алексей Виноградов',
                ],
            [
                'lastName' => 'Полина',
                'firstName' => 'Котова',
                'fullName' => 'Полина Котова',
                'ipContract' => [
                        'number' => '1-10-25',
                        'ammount' => '3500'
                    ]
                ]
            ];
        $jsonUser = json_encode($jsonUser);
        $serializeDataUsers = $serializer->deserialize($jsonUser, 'App\Entity\User[]', 'json');


На выходе получаю массив объектов но без ipContract хотя по логике у Полины Котовой они должны быть, скрин выходных данных прилагаю

5f293a1ee13ce315460721.png

Модель User:

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="users")
 *
 * Defines the properties of the User entity to represent the application users.
 * See https://symfony.com/doc/current/book/doctrine.html#creating-an-entity-class
 *
 * Tip: if you have an existing database, you can generate these entity class automatically.
 * See https://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html
 *
 * @author Ryan Weaver <weaverryan@gmail.com>
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
class User implements UserInterface, \Serializable
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", nullable=true)
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(type="string", nullable=true)
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */
    private $fullName;

    /**
     * @var string
     *
     * @ORM\Column(type="string", unique=true)
     * @Assert\NotBlank()
     * @Assert\Length(min=2, max=50)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(type="string", unique=true, nullable=true)
     * @Assert\Email()
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(type="string", nullable=true)
     */
    private $password;

    /**
     * @var string
     *
     * @ORM\Column(type="text")
     */
    private $roles;


    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $ieInfo;


    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $personalInfo;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\IpContract", mappedBy="users", orphanRemoval=true)
     */
    private $ipContracts;

    /**
     * @ORM\Column(type="boolean", nullable=true, options={"default" : true})
     */
    private $is_active;

    public function __construct()
    {
        $this->ipContracts = new ArrayCollection();
    }
    ................................
    /**
     * @return Collection|IpContract[]
     */
    public function getIpContracts(): Collection
    {
        return $this->ipContracts;
    }

    public function addIpContract(IpContract $ipContract): self
    {
        if (!$this->ipContracts->contains($ipContract)) {
            $this->ipContracts[] = $ipContract;
            $ipContract->setUsers($this);
        }

        return $this;
    }

    public function removeIpContract(IpContract $ipContract): self
    {
        if ($this->ipContracts->contains($ipContract)) {
            $this->ipContracts->removeElement($ipContract);
            // set the owning side to null (unless already changed)
            if ($ipContract->getUsers() === $this) {
                $ipContract->setUsers(null);
            }
        }

        return $this;
    }
}



Модель ipContract:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\IpContractRepository")
 */
class IpContract
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\user", inversedBy="ipContracts")
     * @ORM\JoinColumn(nullable=false)
     */
    private $users;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $number;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $ammount;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $currency;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $partner;

    /**
     * @ORM\Column(type="integer")
     */
    private $status;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $date_begin;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $date_expire;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $file;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\IpInvoice", mappedBy="contract", orphanRemoval=true)
     */
    private $ipInvoices;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\IpAct", mappedBy="contract", orphanRemoval=true)
     */
    private $ipActs;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $lastTransferInvoice;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $fixedAmmount;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $computationAmmount;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $actTemplate = 'default-act.html';

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $invoiceTemplate = 'default-invoice.html';

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $contractTemplate = 'default-contract.html';

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\IpAdditionalAgreement", mappedBy="contract", orphanRemoval=true)
     */
    private $ipAdditionalAgreements;

    public function __construct()
    {
        $this->ipInvoices = new ArrayCollection();
        $this->ipActs = new ArrayCollection();
        $this->ipAdditionalAgreements = new ArrayCollection();
    }

    ...............................................................................................

    public function getUsers(): ?user
    {
        return $this->users;
    }

    public function setUsers(?user $users): self
    {
        $this->users = $users;

        return $this;
    }

    ...............................................................................................
   
}

  • Вопрос задан
  • 198 просмотров
Решения вопроса 1
BoShurik
@BoShurik Куратор тега Symfony
Symfony developer
Symfony serializer как десериализовать массив с объектами?

Плюс, вам надо прописать типы в phpDoc
/**
 * @var \App\Entity\IpContract[]
 *
 * @ORM\OneToMany(targetEntity="App\Entity\IpContract", mappedBy="users", orphanRemoval=true)
 */
private $ipContracts;
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы