Возврат коллекции с помощью настраиваемого преобразователя / поставщика данных на ApiPlatform с GraphQL - PullRequest
1 голос
/ 17 июня 2020

Я работаю с PHP - Symfony 5.

Я хотел бы вернуть коллекцию с помощью graphQL на платформе Api, но у меня проблема:

      "debugMessage": "Service \"App\\DataProvider\\CompaniesCollectionDataProvider\" not found: the container inside \"Symfony\\Component\\DependencyInjection\\Argument\\ServiceLocator\" is a smaller service locator that only knows about the \"App\\Resolver\\CheckRecruiterQueryResolver\", \"App\\Resolver\\ForgotRecruiterQueryResolver\" and \"App\\Resolver\\JobBoard\\FindOffersByCompanyQueryResolver\" services.",

Сначала я создал резолвер, но, глядя на документацию, я понял, что необходимо создать поставщика данных.

К сожалению, это не решило проблему, у меня все еще остается то же сообщение об ошибке ...

Мой поставщик пользовательских данных:

namespace App\DataProvider;


use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;

use App\Entity\Candidate;
use App\Entity\Company;
use Doctrine\Persistence\ManagerRegistry;

class CompaniesCollectionDataProvider implements CollectionDataProviderInterface
{

    private $doctrine;

    public function __construct(ManagerRegistry $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function getCollection
    (string $resourceClass, string $operationName = null, array $context = [])
    {
        $candidateId = $context['filters']['candidate_id'];

        $candidate = $this->doctrine->getRepository(Candidate::class)
            ->findOneBy(['id' => $candidateId]);

        if(empty($candidate->getPosition()))
        {
            $companies =  $this->doctrine->getRepository(Company::class)
                ->findByStoreIsNational();
            // return companies where stores related = is_national

            // getCollection doit retourner un array
            return $companies;

        }
        $companies =  $this->doctrine->getRepository(Company::class)
            ->findByStoreIsNational();

        return $companies;
    }
}

Моя сущность:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use App\DataProvider\CompaniesCollectionDataProvider;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ApiResource(graphql={
 *     "search"={
 *         "collection_query"=CompaniesCollectionDataProvider::class,
 *         "args"={
 *             "candidate_id"={"type"="Int!", "description"="Candidate_id"}
 *         }
 *     },
 *     "create", "update", "delete", "collection_query", "item_query"
 * })
 *
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 * @ORM\Entity(repositoryClass="App\Repository\CompanyRepository")
 * @ORM\Table(name="companies")
 * @UniqueEntity("name")
 */
class Company
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Media", mappedBy="company")
     */
    private $logo;

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

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Store", mappedBy="company")
     */
    private $stores;


    public function __construct()
    {
        $this->stores = new ArrayCollection();
        $this->stories = new ArrayCollection();
        $this->logo = new ArrayCollection();
    }

    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 getLogo(): ?string
    {
        return $this->logo[0];
    }

    public function setLogo(string $logo): self
    {
        $this->logo = $logo;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    public function getDeletedAt(): ?\DateTimeInterface
    {
        return $this->deletedAt;
    }

    public function setDeletedAt(?\DateTimeInterface $deletedAt): self
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * @return Collection|Store[]
     */
    public function getStores(): Collection
    {
        return $this->stores;
    }

    public function addStore(Store $store): self
    {
        if (!$this->stores->contains($store)) {
            $this->stores[] = $store;
            $store->setCompany($this);
        }

        return $this;
    }

    public function removeStore(Store $store): self
    {
        if ($this->stores->contains($store)) {
            $this->stores->removeElement($store);
            // set the owning side to null (unless already changed)
            if ($store->getCompany() === $this) {
                $store->setCompany(null);
            }
        }

        return $this;
    }

    public function addLogo(Media $logo): self
    {
        if (!$this->logo->contains($logo)) {
            $this->logo[] = $logo;
            $logo->setCompany($this);
        }

        return $this;
    }

    public function removeLogo(Media $logo): self
    {
        if ($this->logo->contains($logo)) {
            $this->logo->removeElement($logo);
            // set the owning side to null (unless already changed)
            if ($logo->getCompany() === $this) {
                $logo->setCompany(null);
            }
        }

        return $this;
    }
}

Мой репозиторий:

class CompanyRepository extends AbstractRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Company::class);
    }

    public function findByStoreIsNational() {
        return $this->createQueryBuilder('c')
            ->leftJoin('c.stores', 's')
            ->where('s.isNational = true')
            ->getQuery()
            ->getResult();
    }

Заранее благодарю вас за вашу помощь,

С уважением,

Ромен

1 Ответ

0 голосов
/ 24 августа 2020

Как указано в в документации для настраиваемых запросов , вам необходимо создать настраиваемый преобразователь, а не настраиваемый поставщик данных.

CompaniesCollectionDataProvider должно стать CompanyCollectionResolver и должно реализовывать QueryCollectionResolverInterface.

...