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-&...

问题:

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:

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();
  • 发表于 2018-07-05 11:57
  • 阅读 ( 483 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除