Laravel Eloquent take() 在大型数据集中非常慢或内存耗尽
Laravel Eloquent take() is very slow or memory exhausted in large dataset
我有一个多对多关系:
class Game extends Model
{
public function players()
{
return $this->belongsToMany('App\Player');
}
}
class Player extends Model
{
public function games()
{
return $this->belongsToMany('App\PlayerGame');
}
}
我有 500k+ game_player 个条目,已创建外键。
当我运行用limit=10
时,需要很长时间才能得到结果甚至内存耗尽:
if ($request->filled('limit') && $request->limit > 0) {
return response(Game::findOrFail($id)->players->take($request->limit), 200);
} else {
return response(Game::findOrFail($id)->players, 200);
}
我应该改用 SQL 限制吗?我应该怎么做才好呢?
我有一个多对多关系:
class Game extends Model
{
public function players()
{
return $this->belongsToMany('App\Player');
}
}
class Player extends Model
{
public function games()
{
return $this->belongsToMany('App\PlayerGame');
}
}
我有 500k+ game_player 个条目,已创建外键。
当我运行用limit=10
时,需要很长时间才能得到结果甚至内存耗尽:
if ($request->filled('limit') && $request->limit > 0) {
return response(Game::findOrFail($id)->players->take($request->limit), 200);
} else {
return response(Game::findOrFail($id)->players, 200);
}
我应该改用 SQL 限制吗?我应该怎么做才好呢?