简体   繁体   中英

Symfony2 Doctrine Join Entity

I have a entity with the next join:

class blogComment
{
    ....

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

    ....
}

Now I get successfully all the replies. But I only want to get: where active = true

How to do that?

Oke if you guys recommend to get the comments by query in the controller how to build a nested array to get result like this:

嵌套评论

For solving the part where you only want active replies there are a couple of options:

1) Use some custom DQL in a repository:

$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) Using ArrayCollection::filter() in the getter:

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

3) Using ArrayCollection::matching() ( Collection Criteria API ) in the getter:

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) Use Filters . These can add where clauses to queries regardless of where that query is generated. Please see the docs .

If you want to be able to fetch an entire set of replies, nested and all, in a single query, you need to implement some kind of "tree" of "nested set" functionality. I'd advise you to look at the Tree behavior of l3pp4rd/DoctrineExtensions .

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

Wherever you are obtaining your blog comments to display them (probably on a controller), you need to customise your query so that only the active replies are extracted. Something like:

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

EDIT:

For your new requirement of nested replies, you would need to specify a relationship between a comment entity and its parent comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM