首页 文章

Symfony4 Doctrine2不加入

提问于
浏览
1

我正在尝试使用Thread对象获取Reply对象 .

Thread.php

class Thread
{
    /**
    * One thread can have many replies. This is the inverse side.
    * @ORM\OneToMany(targetEntity="Reply", mappedBy="thread")
    */
    private $replies;

    public function __construct()
    {
        $this->replies = new ArrayCollection();
    }

    /**
    * @return Collection|Reply[]
    */
    public function getReplies(): Collection
    {
        return $this->replies;
    }
}

Reply.php

class Reply
{
    /**
    * @ORM\Column(type="integer")
    */
    private $thread_id;

    /**
    * Many replies have one thread. This is the owning side.
    * @ORM\ManyToOne(targetEntity="Thread", inversedBy="replies", fetch="EAGER")
    * @ORM\JoinColumn(name="thread_id", referencedColumnName="id")
    */
    private $thread;

ThreadController.php

class ThreadController extends Controller
{
    /**
    * @Route("/thread/{id}")
    */
    public function read($id)
    {
        $thread = $this->getDoctrine()->getRepository(Thread::class)->find($id);

        dump($thread); // or dump($thread->getReplies());
    }
}

但由于某种原因,它不起作用 . Thread对象中的ArrayCollection为空且#initialized:false . 属性是私有的还是公共的 .

来自Symfony Profiler的Doctrine查询,其中没有JOIN:

SELECT 
  t0.id AS id_1, 
  t0.user_id AS user_id_2, 
  t0.title AS title_3, 
  t0.body AS body_4, 
  t0.created_at AS created_at_5, 
  t0.updated_at AS updated_at_6 
FROM 
  thread t0 
WHERE 
  t0.id = ?

哪里可以成问题?谢谢

1 回答

  • 0

    除非您明确尝试访问相关对象,否则Doctrine不会自动获取相关对象 . https://symfony.com/doc/current/doctrine/associations.html#fetching-related-objects

    调用 $thread->getReplies() 实际上会发出第二个请求来获取与该线程相关的回复 .

    另一种解决方案是在实体存储库中定义自定义方法,并显式加入两个表 .

    以下是Symfony文档中的一个示例

    // src/Repository/ProductRepository.php
    public function findOneByIdJoinedToCategory($productId)
    {
        return $this->createQueryBuilder('p')
            // p.category refers to the "category" property on product
            ->innerJoin('p.category', 'c')
            // selects all the category data to avoid the query
            ->addSelect('c')
            ->andWhere('p.id = :id')
            ->setParameter('id', $productId)
            ->getQuery()
            ->getOneOrNullResult();
    }
    

    https://symfony.com/doc/current/doctrine/associations.html#joining-related-records

相关问题