我正在尝试获取带有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的文档查询,其中没有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 = ?
哪里有问题?谢谢
答案 0 :(得分: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