php - High CPU usage with Laravel Eloquent filtering -


i need pick out teams user rostered in, , eloquent code it:

$teams = team::orderby('created_at', 'desc')->get()->filter(function($team) use ($user) {     return $team->inteam($user); }); 

the rosters teams arrays of user ids, stored string in database.

this inteam function:

public function inteam($user) {     $id = $user->id;     $players = $this->getplayers();      foreach ($players $p)     {         if (is_null($p)) continue;         if ($p == $id) return true;     }     return false; } 

my server cpu usage spikes 60%+ on apache2 , 30% on mysqld whenever page code loaded , cannot figure out why. using filter() on team model cleanest way i've found of doing need , causing issues, bringing site halt when enough users load page.

is there way can optimize filtering or need restructure way database holds roster information?

edit: i've updated code use find_in_set , managed bring cpu time down 5s 8s. still not ideal, however.

$teams = team::orderby('id', 'desc')->whereraw("find_in_set(" . $user->id . ", players_list)")->get(); 

i have no idea how i'd go normalizing db this, players_list column has different length according event team tied to, hence comma separated strings.

filtering mean retrieve datas mysql , searching big array containing result.

for large datasets, recommand using sql condition instead php-side filtering.

please, post more database if want working snippet. otherwize, check documentation / wherein, etc : http://laravel.com/docs/5.0/eloquent#basic-usage


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -