Abdel5
Abdel5

Reputation: 1120

How to check if item is related to certain other item in many to many relationship?

I have document entity with one to many relation to documentstags entity.

How may I check whether certain document is related to documentstags with certain "tag" column value?

Documents entity:

/**
* @ORM\OneToMany(targetEntity="Documentstags", mappedBy="documentid")
*/
protected $tags;

Documentstags entity:

/**
     * @ORM\Column(type="string", length=220)
     */
    protected $tag;

How may I check whether document A is related to Documentstags item which tag value e.g. B?

Currently I have implemented the following code as function of Documents entity but it does not seems to be effecient:

$tags = $this->getTags();
        $is_zatwierdzony = false;
        foreach($tags as $tag)
        {
            if($tag.tag == $this->avaliabletags['zatwierdzony']['name']) $is_zatwierdzony = true
        }

Upvotes: 1

Views: 84

Answers (1)

waldek_h
waldek_h

Reputation: 930

U can use Criteria class:

for example:

...
use Doctrine\Common\Collections\Criteria;
...

public function getMatchingTags() 
{
    $criteria = Criteria::create()
                ->where(Criteria::expr()->eq("tag", $this->avaliabletags['zatwierdzony']['name']));

    $tags = $this->getTags()->matching($criteria);

    #do something with matching tags
}

Doctrine2 documentation: Filtering Collections

Upvotes: 2

Related Questions