php - Optimizing Queries - Eager loading takes too much memory -
php - Optimizing Queries - Eager loading takes too much memory -
i have next tables:
user (about 1.000 rows) fans (about 100.000 rows) - user has many fans, fan belongs 1 user likes (about 100.000 rows - user has many likes, belongs 1 usernow want have table with
user name number of fans number of likesit big table , utilize jquery datatable have pagnition here server side.
i have set relations , out set table:
$users = user::get(); foreach ($users $user) { echo $user->name; echo $user->fans()->count(); echo $user->likes()->count(); }
this lot of queries , want optimize. first seek using eager loading.
$users = user::with('fans', 'likes')->get();
but seems havy server memory. on local environment have 16 mb memoriy size php scripts. , tries allocate more.
is normal? best solution give scripts more memory? how else optimize queries?
if want count number of records there's no point records count them, 201000 rows. should add together :
public function fanscountrelation() { homecoming $this->hasone('fan')->selectraw('user_id, count(*) count') ->groupby('user_id'); } public function likescountrelation() { homecoming $this->hasone('like')->selectraw('user_id, count(*) count') ->groupby('user_id'); } public function getlikescountattribute() { homecoming $this->likescountrelation ? $this->likescountrelation->count : 0; } public function getfanscountattribute() { homecoming $this->fanscountrelation ? $this->fanscountrelation->count : 0; }
to user
model , 1000 user rows + aggregate info fans , likes.
and can use:
$users = user::with('fanscountrelation', 'likescountrelation')->get(); foreach ($users $user) { echo $user->name; echo $user->likes_count; echo $user->fans_count; }
however should rethink if need it. 1000 rows normal usage much. if utilize export purposes that's fine, if display in admin panel example, should utilize paginating that.
and in case takes much time, should create sure have indexes fans
, likes
tables user_id
column. should speed queries lot.
php mysql laravel laravel-4 eloquent
Comments
Post a Comment