Neha
Neha

Reputation: 2281

How to get relation of relation Count in laravel?

i have laravel models

Category: id,name

public function posts(){
    return $this->hasMany(PostCategory::class,'category_id','id');
}

PostCategory : post_id, category_id

public function post(){
    return $this->belongsTo(Post::class,'post_id');
}

POST: id, ..so on

public function solutions(){
    return $this->hasMany(PostSolution::class,'post_id','id');
 }

I need to get count of all posts fall under a category and also solutions under one category.. there is no direct relation of category and solution so how to get count of solutions in one category.

$categories = Category::withCount('posts')->get();

Upvotes: 0

Views: 52

Answers (1)

Basharmal
Basharmal

Reputation: 1384

I think use hasManyThrough relation

// Category Class

public function solutions()
{
    return $this->hasManyThrough(PostSolution::class, Post::class);
}

// Then get the data in the same old manner
$categories = Category::->withCount('posts')->get();

I hope this will help

Upvotes: 1

Related Questions