RednBlack
RednBlack

Reputation: 102

Laravel morphedByMany where condition and count

I have two tables: Posts and Pages that share one table for tags (morphToMany).

My tables and relations:

Table: Tags id, name

public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
public function pages()
{
return $this->morphedByMany('App\Page', 'taggable');
}

Table: Posts id, name, active

public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}

Table: Pages id, name, active

public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}

How can I get all tags and count from both tables where pages.active and posts.active

I tried this query but this query returns only tags that are in both models:

Tag::whereHas("posts", function($q) {

$q->where("posts.active", "=", 1);

})->whereHas("pages", function($q) {

$q->where("pages.active", "=", 1);

})->get();

I need a query that can return tag if exists in one of the models but where active = 1.

Upvotes: 2

Views: 2653

Answers (1)

rkj
rkj

Reputation: 8287

You can try it

$tags = Tag::where( function( $query ){
        $query->whereHas('posts', function ( $subquery ){
            $subquery->where('active', 1 );
        })
        ->orWhereHas('pages',function ( $subquery ){
            $subquery->where('active', 1 );
        });
      })->withCount('posts','pages')->get();

Upvotes: 2

Related Questions