Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 任何简单计算与不同';其中';条款?_Laravel_Eloquent_Count_Relationship - Fatal编程技术网

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); }
    ]);