【问题标题】:Any way to do simple count of relations with different 'where' clauses?有什么方法可以简单地计算不同“where”子句的关系吗?
【发布时间】:2019-05-06 08:22:07
【问题描述】:

我在用户模型中有这种关系

public function bulletins()
{
    return $this->hasMany('App\Bulletins','owner');
}

在控制器中我得到了公告的数量:

dump(
 User::where('id',Auth::id())
  ->withCount('bulletins')
  ->where('status','=',1)
  ->first()
);

这计数所有状态 = 1,但我还需要状态 = 0 和不同表列中的其他参数。在外面我想要这样的东西:

bulletin_counters->total =10//all
bulletin_counters->active =20//status=1
bulletin_counters->archive =30//status=0
bulletin_counters->deleted =40//deleted=1
etc...

最好的方法是什么?我知道我可以做很多查询并手动分配这些变量。

【问题讨论】:

    标签: laravel eloquent count relationship


    【解决方案1】:

    您应该能够自定义由 withCount 生成的查询

    尝试以下方法:

     ->withCount([
        'bullentins as bullentins_total',
        'bullentins as bullentins_active' => function($query) { $query->where('status', 1); },
        'bullentins as bullentins_archive' => function($query) { $query->where('status', 0); },
        'bullentins as bullentins_deleted' => function($query) { $query->where('deleted', 1); }
        ]);
    

    【讨论】:

      猜你喜欢
      • 2015-12-18
      • 2022-11-01
      • 2017-02-18
      • 2012-01-27
      • 2012-03-17
      • 1970-01-01
      • 2010-12-12
      • 2021-07-25
      • 1970-01-01
      相关资源
      最近更新 更多