mysql - laravel 4 - how to Limit (Take and Skip) for Eloquent ORM? -
tl;dr
can limit eloquent orm query using take()
, skip()
resulting mysql query limited, , doesn't have return entire dataset?
if so, how modify:
$test = user::find(1)->games->toarray();
to include limit 3 offset 2
?
tables:
users games usergames -- id -- id -- user_id -- name -- name -- game_id -- steam_id
models:
class user extends eloquent { public function games() { return $this->belongstomany('game', 'usergames', 'user_id', 'game_id'); } } class game extends eloquent { public function users() { return $this->belongstomany('user', 'usergames', 'user_id', 'game_id'); } }
limit in query builder
using regular laravel query builder can games
belong user
of id 1, , limit result take()
, skip()
:
$test = db::table('games') ->join('usergames', 'usergames.game_id', '=', 'games.id') ->where('usergames.user_id', '=', '1')->take(3)->skip(2)->get();
by listening illuminate.query
event can see query generated is:
select * `games` inner join `usergames` on `usergames`.`game_id` = `games`.`id` `usergames`.`user_id` = ? limit 3 offset 2
limit in eloquent orm
when try recreate same query eloquent:
$test = user::find(1)->games->take(2)->toarray();
i'm able use take
adding skip
causes error. resulting query not contain limit:
select `games`.*, `usergames`.`user_id` `pivot_user_id`, `usergames`.`game_id` `pivot_game_id` `games` inner join `usergames` on `games`.`id` = `usergames`.`game_id` `usergames`.`user_id` = ?
so seems entire result being queried first, not ideal when dealing large data sets.
question:
is possible limit eloquent orm query @ mysql query level limits result, equivalent limit 3 offset 2
?
user::find(1)->games()->take(3)->skip(2)->get();
i think should give collection. :)
->games
give collection, ->games()
offer query builder instance.
enjoy laravel!
Comments
Post a Comment