Agris
Agris

Reputation: 105

Symfony3 doctrine check if collection empty

  1. have 3 entity Docs, DocsPerm, DocsList
    1. in doctrine i select only Docs + DocsPerm.
    2. Then i check Docs->getDocsList->isEmpty() then all DocsList are selected from database
    3. How to check if DocsList is empty or selected without cause to select all elements from database? Thanks.

EDIT: example

  1. have 2 controllers. ( one with Docs+perm, second Docs+DocList)
  2. have 1 twig template for 2 controlers. Here i wan't to check

{% if Docs.DocsList is empty %} return false or

{% if Docs.DocsList.isEmpty %}return false or

{% if Docs.DocsList.first is defined %} get error.

first two get all DocsList elements from db witch i don't need.

Upvotes: 0

Views: 1187

Answers (1)

Dmitry Malyshenko
Dmitry Malyshenko

Reputation: 3051

Make a service.

Something like

$docListChecker->isEmpty($docs);

End then make a query that will fetch only count of entities, but not entities themselves.

$result = $qb->select('COUNT(l)')
                ->from('YourBundle:docsList' , 'l')
                ->leftJoin('l.docs.','d')
                ->where('d.id = :id')
                ->setParameter('id', $id)
                ->getQuery()
                ->getSingleScalarResult();

This service you can pass to twig and check your list as

 {% if checker.isEmpty(Docs.DocsList) %}

Or even you can make a twig filter and use it like

 {% if Docs.DocsList | isListEmpty %}

Upvotes: 1

Related Questions