0

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();
4
  • 1
    Are you sure, that a post category belongs to a single post? Shouldn't it be the other way around (or that a post belongs to many post categories)? Commented Mar 25, 2021 at 12:27
  • Thanks Has Many Through is working! Commented Mar 25, 2021 at 12:41
  • The person who answered this has deleted their comment so i am not able to upvote. Commented Mar 25, 2021 at 12:49
  • @Basharmal yes you are right! single post belongs to many categories Commented Mar 25, 2021 at 12:50

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.