murilo

Count Posts where tag = 1

Posted 7 months ago by murilo

Hello , I have a question .

I have this code , It is working -

CATEGORY CONTROLLER

       return  CategoryPost::select(['id' ,'title'])
        ->withCount('Posts')
->get();

CATEGORY MODEL

  public function Posts(){
        return $this->hasMany(Post::class , 'category_id' );
    }

BUT I want to count all the posts in this category with TAG = 1 .

It wold be something like that -

CATEGORY CONTROLLER

       return  CategoryPost::select(['id' ,'title'])
        ->with('CountPostWithTagOne')
->get();

CATEGORY MODEL

  public function Posts(){
        return $this->hasMany(Post::class , 'category_id' );
    }

  public function CountPostWithTagOne(){
        return $this->Posts->where('tag_id' , 1 )->count();
    }

But this second example does not work .

Please sign in or create an account to participate in this conversation.