簡體   English   中英

Symfony2學說加入實體

[英]Symfony2 Doctrine Join Entity

我有一個具有下一個聯接的實體:

class blogComment
{
    ....

    /**
     * @ORM\OneToMany(targetEntity="BlogComment", mappedBy="replyTo")
     */
    protected $replies;

    ....
}

現在,我成功獲得了所有答復。 但我只想得到: where active = true

怎么做?

好吧,如果你們建議通過控制器中的查詢來獲取注釋,如何構建嵌套數組以獲取如下結果:

嵌套評論

要解決您只希望得到積極答復的部分,有兩種選擇:

1)在存儲庫中使用一些自定義DQL:

$dql = 'SELECT bc FROM BlogComment bc WHERE bc.replyTo = :id AND bc.active = :active';
$q = $em->createQuery($dql)
    ->setParameters(array('id' => $id, 'active' => true));

2)在getter中使用ArrayCollection::filter()

public function getReplies()
{
    return $this->replies
        ->filter(function ($reply) {
            return $reply->isActive();
        })
        ->toArray();
}

3)在getter中使用ArrayCollection::matching()Collection Criteria API ):

use Doctrine\Common\Collections\Criteria;

// ...

public function getReplies()
{
    $criteria = new Criteria::create()
        ->where(Criteria::expr()->eq('active', true));

    return $this->replies
        ->matching($criteria)
        ->toArray();
}

4)使用過濾器 這些可以在查詢中添加where子句,而不管查詢在何處生成。 請參閱文檔

如果希望能夠在單個查詢中獲取嵌套的全部答復集,則需要實現某種“嵌套集”功能的“樹”。 我建議您查看l3pp4rd / DoctrineExtensionsTree行為。

http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html

無論在何處獲得博客評論以顯示它們(可能在控制器上),都需要自定義查詢,以便僅提取活動答復。 就像是:

$query = $em->createQuery('SELECT b FROM blogComment b JOIN b.replies r WHERE r.active = :active');
$query->setParameter('active', true);
$blogComments = $query->getResult();

編輯:

對於您對嵌套回復的新要求,您需要指定評論實體與其父評論之間的關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM