Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Lazy Eager Load Count

I'm ideally looking for a function like

load('relationship')

but which loads a count in the same way

withCount('relationship')

works for eager loading.

I'm thinking it is going to be called loadCount('relationship')

like image 982
edlouth Avatar asked Oct 13 '16 11:10

edlouth


People also ask

What is lazy vs eager loading in Laravel?

Lazy Loading vs. Eager Loading. 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 BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

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.


3 Answers

loadCount() is available since Laravel 5.8

$post->loadCount('comments');

$post->comments_count;

Docs

like image 142
Maksim Ivanov Avatar answered Oct 17 '22 01:10

Maksim Ivanov


As of Laravel 5.2, this functionality is built-in.

Provided you have a hasMany relationship between Post and Comment, do:

<?php

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

You can even eager load relationships count by default by declaring this in your model:

<?php

// Post model

protected $withCount = ['comments'];
like image 41
rzb Avatar answered Oct 17 '22 01:10

rzb


This solution works great for me:

Create a new hasOne relationship on the related model and add a raw select to the query for the count. For example, if you want to eager load the number of tasks for a given user, add this to the User Model:

public function taskCount()
{
    return $this->hasOne('App\Task')
    ->selectRaw('user_id, count(*) as count)
    ->groupBy('user_id');
}

And then eager load the count like this:

$user = User::where('email', $email)->with('taskCount')->first();

And access the count like this:

$taskCount = $user->task_count->count;
like image 25
hubrik Avatar answered Oct 17 '22 02:10

hubrik