1

I have this script.

It fetch the rows from DB and choose the row which belongs to a Category(CatData).

getCatDatas() returns \Doctrine\Common\Collections\ArrayCollection() class.

So it can use contain() to check.

However I want to put this method in DQL itself, is there any practice??

$result = array();
$articles = $em->createQuery("SELECT a FROM DefaultBundle:ArticleData a ")
    ->getResult();

foreach ($articles as $a){// I want to put this function in DQL.
    if ($a->getCatDatas()->contain($cat)){
        array_push($articles,$result);
    }
}

2 Answers 2

2

Yes, you can use DQL and do a where condition on relation.

You can find more info here: https://symfonycasts.com/screencast/symfony3-doctrine-relations/relation-query

In particular, the method findAllRecentNotesForGenus in GenusNoteRepository.

I think you can do something similar:

public function findPostsByCategoryData(CategoryData $cat)
{
    return $this->createQueryBuilder('a')
        ->andWhere('a.catDatas = :cat')
        ->setParameter('cat', $cat)
        ->getQuery()
        ->execute();
}
1
  • Thank you I have progress, It shows the error Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.. However I found the solution here stackoverflow.com/questions/19161223/…
    – whitebear
    Nov 21, 2019 at 4:23
0

@Alessandro Filira started in the right direction but forgot to take into account that this is a to-many relationship that you want to filter on.

Doctrine supports MEMBER OF operator, which works a bit like IN but in the opposite direction. It allows you to check if the specific value that you have is found as an element in the related group.

So the code should be like:

public function findPostsByCategoryData(CategoryData $cat): array
{
    return $this->createQueryBuilder('a')
        ->andWhere(':cat MEMBER OF a.catDatas')
        ->setParameter('cat', $cat)
        ->getQuery()
        ->getResult();
}

See Doctrine Docs for MEMBER OF usage: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/dql-doctrine-query-language.html (use Ctrl+F and "member of")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.