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
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.
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.
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.
I manage to solve it by:
$posts = Post::with('author')->order_by('id', 'desc')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With