我使用DQL进行自定义查询,并且对象没有看到该方法

时间:2018-05-16 19:57:28

标签: php symfony oop doctrine dql

当我学习Symfony时,我在DQL中遇到了自定义查询的问题,有一个指向doc https://symfony.com/doc/current/doctrine.html#querying-with-dql-or-sql的链接 我做了同样的功能:

<?php

namespace App\Repository;

use App\Entity\CatPost;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method CatPost|null find($id, $lockMode = null, $lockVersion = null)
 * @method CatPost|null findOneBy(array $criteria, array $orderBy = null)
 * @method CatPost[]    findAll()
 * @method CatPost[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class CatPostRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, CatPost::class);
    }

    public function findAllCategoriesConnectedToPost($id) :array
    {
        $entityManager = $this->getEntityManager();

        $query = $entityManager->createQuery(
            'SELECT cat.id_cat 
             FROM App\Entity\CatPost cat 
             WHERE cat.id_post = :idPost'
        );
        $query->setParameter('idPost', $id);

        return $query->execute();
    }
}

实体类:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

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

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

    public function getId()
    {
        return $this->id;
    }

    public function getIdPost(): ?int
    {
        return $this->id_post;
    }

    public function setIdPost(int $id_post): self
    {
        $this->id_post = $id_post;

        return $this;
    }

    public function getIdCat(): ?int
    {
        return $this->id_cat;
    }

    public function setIdCat(int $id_cat): self
    {
        $this->id_cat = $id_cat;

        return $this;
    }
}

然后我想在我的控制器中使用它:

/App/Controller/ArticleController

$categories = $this->getDoctrine()
->getRepository(CatPost::class)
->findAllCategoriesConnectedToPost($id);

var_dump($categories);
die();

结果,我得到了空数组,PhpStorm告诉我“找不到方法” 你有任何想法如何解决它?

1 个答案:

答案 0 :(得分:0)

您确定要链接到实体中的存储库吗?

/**
* CatPost
*
* @ORM\Entity(repositoryClass="App\Repository\CatPostRepository")
*/
class CatPost

您可以在同一个文档页面上进一步查看 - https://symfony.com/doc/current/doctrine.html#creating-an-entity-class