php - Query Builder inside entity - Doctrine -


i'm looking better way write function. it's inside doctrine entity model

public function getcompanysubscriptions() {     foreach ($this->subscriptions $key => $value) {         if ($value->getplan()->gettype() == 'e' && $value->getactive()) {             return $value;         }     }     return null; } 

$this->subscriptions many-to-one collection , can have different "types" (but 1 of them type "e").

problem is: if company has many $subscriptions function slow return 1 of type "e" need check when building view twig. solution use querybuilder, haven't found way use directly entity model.

you cannot use querybuilder inside entity, instead can use doctrine criteria filtering collections (on sql level). check documentation chapter 8.8. filtering collections more details on criteria.

if collection has not been loaded database yet, filtering api can work on sql level make optimized access large collections.

for example active subscriptions:

$subscriptions = $this->getcompanysubscriptions();  $criteria = criteria::create()     ->where(criteria::expr()->eq("active", true));  $subscriptions = $subscriptions ->matching($criteria); 

like can solve performance issues, since collection loaded database using conditions criteria directly.

the problem in case might need join on plan, joining not possible in criteria. if joining necessary should consider using custom query join conditions in company entityrepository (for example querybuilder).

note. foreach in question can rewritten using the filter method arraycollection class. filter takes predicate , elements satisfying predicate returned. here in doctrine 2 class documentation more info.

your predicate like:

$predicate = function($subscription){     $subscription->getplan()->gettype() == 'e' && $subscription->getactive(); } 

and then:

return $this->subscriptions->filter($predicate); 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -