【发布时间】:2021-03-27 20:49:11
【问题描述】:
我有一个多对多的关系:
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 限制吗?又该如何做好呢?
【问题讨论】:
标签: mysql laravel eloquent limit laravel-collection