Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Laravel News:
Optimize Eloquent Queries with Eager Loading
Aug 11, 2017 @ 14:23:29

On the Laravel News site they've posted a tutorial sharing some of the basics around the optimizing Eloquent queries with the help of its own "eager loading" feature.

Object Relational mapping (ORM) makes working with databases amazingly simple. While defining database relationships in an object-oriented way makes it easy to query related model data, developers might not pay attention to the underlying database calls.

A standard database optimization for an ORM is eager-loading related data. We will set up some example relationships and then walk through how queries change with and without eager loading. I like to get my hands directly on code and experiment with things, and I hope to illustrate how eager loading works with some examples will further help you understand how to optimize your queries.

They start with a classic example of the "N+1 problem" when working with database records and how, without you knowing, you might be causing it with lazy loading. The article then talks about eager loading vs lazy loading and how they differ in most ORMs. It then covers Eloquent, setting up some migrations for an example blog application and creating the relationships between Author (user) and the Posts. The models are created and seeders are built to populate the tables with Faker data. Finally it gets to the use of eager loading, making use of the "with" functionality to modify the query structure behind the scenes. The post finishes with mentions of two other eager loading types - lazy eager loading and nested eager loading.

tagged: optimize query eager loading laravel eloquent performance nplusone

Link: https://laravel-news.com/eloquent-eager-loading


Trending Topics: