Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Model Eager loading and ordering

I'm new to Laravel and thought it be cool to purchase the Codehappy ebook by Dayle Rees.

I just finished the blog tutorial and thought a bit on how he retrieved the posts from the Post model. Coming from a .net (ASP.NET MVC) background I think it will be important to order the posts while eager loading the author.

He eager loads the model like this.

$posts = Post::with('author')->get();

My question is where can you use the "order_by" clause? the order_by itself works when I use:

$posts = Post::order_by('id', 'desc')->get();

Regards RaVen

like image 913
RaVen Avatar asked Jun 13 '12 11:06

RaVen


People also ask

How eager loading works in laravel?

Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.

What is difference between eager and lazy loading laravel?

While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.

What is lazy loading & eager loading in laravel?

The main difference between eager and lazy loading is eager loading get all data with relationship records in single query and lazy loading require N+1 queries for getting main model and relation data. Eager loading run single query whereas lazy loading run N+1 queries.


1 Answers

I manage to solve it by:

$posts = Post::with('author')->order_by('id', 'desc')->get();
like image 127
RaVen Avatar answered Oct 05 '22 22:10

RaVen