php - Find total with only the first iteration from relationship -


in scenario have ticket model , ticketreply model.

i can grab replies ticket $ticket->replies.

considering status 1 or 3 of ticket or reply means state open/unresolved, how find total of tickets open eloquent way.

$tickets = ticket::all();  $tickets_open = 0;  foreach($tickets $t) {     $tickets_open++;      if(($t->replies()->first()->status == 2) || ($t->status == 2))     {         $tickets_open--;     } }  return $tickets_open; 

is there more efficient way of doing eloquent?

since query run each iteration.

if there not, can convert $tickets array , iterate it.

update:

$t->replies()->first()->status causing 1+n or without eager loading.

i changed $t->replies->first()->status , 1+n gone. rookie mistake believe.

you can use eager loading reduce number of queries.

$tickets = ticket::with('replies')->get(); 

doing this, instead of running 1+n queries, end running 2 sql queries:

select * tickets  select * ticketreplies ticket_id in (1, 2, 3, 4, 5, ...) 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -