我添加了一个自定义属性年龄(以月为单位),例如:
//铸造,以便我可以使用Carbon实例
protected $dates = ['date_of_birth'];
//以月为单位返回年龄
public function getAgeAttribute(){
if(empty($this->date_of_birth){
return null;
}
return $this->date_of_birth->diffInMonths();
}
然后,我附加了年龄,以便可以在全球范围内使用年龄,例如:
protected $appends = ['age'];
现在,我需要在生成基于年龄月份显示的报告时使用年龄月份:
如何根据用户集中的年龄进行过滤?
//常规设置
$ages = [10, 20, 30, ...];
$users = User::get();
$requiredDetail = [];
尝试1
我尝试使用where子句,但不起作用
foreach($ages as $age){
$requiredDetail[$age] = $users->where('age', $age)->count();
}
尝试2
我尝试使用收集过滤器,但无法正常工作
foreach($ages as $age){
$requiredDetail[$age] = $users->filter(function($user) use ($age){
return $user->age == $age;
});
}
问题是从收藏集中检索年龄后如何过滤年龄?
采用 WhereIn
$requiredDetail = $users->whereIn('age', $age)->count();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句