Laravel morphedByMany where condition and count


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('AppPost', 'taggable');
}
public function pages()
{
return $this->morphedByMany('AppPage', 'taggable');
}



Table: Posts
id, name, active


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



Table: Pages
id, name, active


public function tags()
{
return $this->morphToMany('AppTag', '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.




1 Answer
1



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();





thnx bro your legend. i use like this: Tag Name - ((($tag- >posts_count+$tag->pages_count) ? is there a way to sum both counts from query or Iam doing it right?
– RednBlack
Jul 1 at 1:54





glad it works, and that is fine be simple
– rkj
Jul 1 at 4:05





OK. Thank you very much.
– RednBlack
Jul 1 at 23:24






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API