Laravel 任何简单计算与不同';其中';条款?
我在用户模型中有这种关系Laravel 任何简单计算与不同';其中';条款?,laravel,eloquent,count,relationship,Laravel,Eloquent,Count,Relationship,我在用户模型中有这种关系 public function bulletins() { return $this->hasMany('App\Bulletins','owner'); } 在控制器I中,获取公告的计数: dump( User::where('id',Auth::id()) ->withCount('bulletins') ->where('status','=',1) ->first() ); 此计数全部为status=1,但我还需
public function bulletins()
{
return $this->hasMany('App\Bulletins','owner');
}
在控制器I中,获取公告的计数:
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...
哪种方法最好?我知道我可以执行许多查询并手动分配这些变量。您应该能够自定义由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); }
]);