Tuesday 15 May 2012

Laravel: Improved pivot query -



Laravel: Improved pivot query -

i querying next , create 130 queries, want optimise , cut down number of queries, have set upped model , controllers next way.

post modal

class post extends eloquent { public function categories () { homecoming $this->belongstomany('category', 'category_post'); } }

category modal

class category extends eloquent { public function posts () { homecoming $this->belongstomany('post', 'category_post'); } }

and in controller, using next query, next query is, querying results based on category id.

$category = category::with('posts')->where('id','=',$id)->paginate(10)->first(); homecoming response::json(array('category' => $category));

if can give me hand optimise query, greatful.

you wrong, doesn't create 130 queries.

it create next 3 queries:

select count(*) aggregate `categories` `id` = '5'; select * `categories` `id` = '5' limit 10 offset 0; select `posts`.*, `posts_categories`.`category_id` `pivot_category_id`, `posts_categories`.`post_id` `pivot_post_id` `posts` inner bring together `posts_categories` on `posts`.`id` = `posts_categories`.`post_id` `posts_categories`.`category_id` in ('5');

but question want paginate. paginate categories , doesn't create much sense because there's 1 category selected $id.

what want is:

$category = category::where('id','=',$id)->first(); $posts = $category->posts()->paginate(10);

and 1 time again create 3 queries:

select * `categories` `id` = '5' limit 1; select count(*) aggregate `posts` inner bring together `posts_categories` on `posts`.`id` = `posts_categories`.`post_id` `posts_categories`.`category_id` = '5'; select `posts`.*, `posts_categories`.`category_id` `pivot_category_id`, `posts_categories`.`post_id` `pivot_post_id` `posts` inner bring together `posts_categories` on `posts`.`id` = `posts_categories`.`post_id` `posts_categories`.`category_id` = '5' limit 10 offset 0;

if improve it, need not utilize eloquent in case , utilize join - worth it? need manually paginate results without paginate() won't want want achieve.

edit

what is:

you posts belongs category (but in fact want paginate 10 of them) for each post want display categories belongs to.

to lower number of queries should use:

$category = category::where('id','=',$id)->first(); $posts = $category->posts()->with('categories')->paginate(10);

and display should use:

foreach ($posts $p) { echo $p->name.' '."<br />"; foreach ($p->categories $c) { echo $c->name."<br />"; } }

it should lower number queries 4 130

laravel laravel-4

No comments:

Post a Comment