[英]Symfony4 Doctrine2 doesn't join
我試圖獲取帶有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 = ?
哪里可能有問題? 謝謝
Docctrine不會自動獲取相關對象,除非您明確嘗試訪問它們。 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.