我在用户模型中具有这种关系
public function bulletins()
{
return $this->hasMany('App\Bulletins','owner');
}
在控制器中,我得到了公告的数量:
dump(
User::where('id',Auth::id())
->withCount('bulletins')
->where('status','=',1)
->first()
);
此状态全部为status = 1,但我还需要status = 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...
哪个是最好的方法?我知道我可以进行很多查询并手动分配此变量。
答案 0 :(得分:2)
您应该能够自定义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); }
]);