kjdion84
kjdion84

Reputation: 10044

withCount() on relation hasMany

I'm trying to use withCount() on a relationship of a relationship. The error I'm getting is Method Illuminate\Database\Query\Builder::forums.threads does not exist..

Given these models:

class Category extends Model
{
    public function forums()
    {
        return $this->hasMany('App\Forum');
    }
}

class Forum extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function threads()
    {
        return $this->hasMany('App\Post')->orderByDesc('created_at');
    }
}

Consider the following in my controller:

public function index()
{
    $categories = Category::with('forums')->withCount('forums.threads')->orderBy('order')->get();

    return view('home', compact('categories'));
}

And the following in my view:

@foreach($categories as $category)
    {{ $category->title }}<br>
        @foreach($category->forums as $forum)
            {{ $forum->title }}<br>
            {{ $forum->threads_count }}
        @endforeach
@endforeach

I know I can simply remove the withCount from the controller and use $forum->threads->count(), but is it possible to query counts the way I want?

If so, how? I'd like this to be as fast as possible by eager loading the counts (without loading all of the actual threads, of course).

Upvotes: 3

Views: 2394

Answers (2)

QaMar ALi
QaMar ALi

Reputation: 237

you dont need to load the threads you can use $forum->threads()->count() It will return the count of thread without loading them

Upvotes: -1

Sohel0415
Sohel0415

Reputation: 9853

Try withCount() inside closure:

$categories = Category::with(['forums'=>function($q){
       $q->withCount('threads');
    }])->orderBy('order')->get();

Upvotes: 5

Related Questions