Performance: One-to-many (hasMany)
This affects how many database queries are run and how much data is loaded into memory, impacting page load speed and responsiveness.
<?php $posts = App\Models\Post::with('comments')->get(); foreach ($posts as $post) { echo $post->comments->count(); }
<?php
$posts = App\Models\Post::all();
foreach ($posts as $post) {
echo $post->comments->count();
}
| Pattern | Database Queries | Memory Usage | Response Time | Verdict |
|---|---|---|---|---|
| Lazy loading (N+1 queries) | N+1 queries | Higher due to repeated loads | Slower with many related items | [X] Bad |
| Eager loading (with) | 2 queries | Lower and predictable | Faster and scalable | [OK] Good |
hasMany relationship represent in Laravel?hasMany means one model owns many related models.hasMany is used when one record relates to multiple records in another table.hasMany relationship in a Laravel model?hasMany() defines one-to-many relations.hasMany(Comment::class), which is correct syntax.$post->comments->count() output if the post has 3 related comments?class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
}
}comments() method returns all related Comment models as a collection.$post->comments->count() counts the number of related comments. Since there are 3, it returns 3.hasMany relationship definition?public function comments() {
return $this->hasMany('App\Models\Comment');
}Comment::class.Comment::class avoids typos and enables IDE support.User model and a Post model. Each user can have many posts. How do you retrieve all posts for a user with ID 5 using Eloquent's hasMany relationship?User::find(5) fetches the user with ID 5.->posts returns all posts related to that user.Pass the test and this pattern moves unknown