Eager loading in Laravel is a technique used to retrieve related models or relationships with the primary model in a more efficient manner. By using eager loading, you can reduce the number of database queries and improve performance when fetching data.
Here's an example of how to use eager loading in Laravel:
Define the relationship in your Eloquent model:
s
class Post extends Model { public function comments() { return $this->hasMany(Comment::class); } }
s
- Retrieve the primary model with its related models using eager loading:
s
$posts = Post::with('comments')->get();
s
In this example, we're fetching all the posts and their associated comments. The
with()
method specifies the relationship name (comments
in this case) to be eagerly loaded.Access the related models in your code:
s
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
// Access the comment data
}
}
s
By eager loading the comments, you can access them directly on the
$post
object without triggering additional queries for each post.
Eager loading can be used with various types of relationships in Laravel, such as hasOne
, hasMany
, belongsTo
, belongsToMany
, and more. It helps to optimize database queries and improve the efficiency of fetching related data, especially when dealing with large datasets or complex relationships.
No comments:
Post a Comment