Laravel自定义集合实现月度日期与用户评分关联展示问题
问题:生成当月日期对应Lesson评分的自定义Collection
我想要为拥有多个Session的特定User创建自定义Collection,目标是生成一张包含当月日期及对应Lesson评分的表格(示例表格显示日期1-30,仅4日有评分5)。
初始实现代码
$user = User::where('id', $request->id)->with('lessons')->first(); $a = 1; $collection = new Collection(); while ($a <= date('d')) { $date = new Carbon(date('Y').date('m').$a); $collection->push((object)[ 'date' => $a, 'rating'=>$user->lesson->where('date', $date->toDateString())->first() ? $user->lesson->where('date', $date->toDateString())->first()->get('rating') : null ]); $a++; }
我认为问题出在这段代码:
'rating'=>$user->lesson->where('date', $date->toDateString())->first() ? $user->lesson->where('date', $date->toDateString())->first()->get('rating') : null
该逻辑返回的集合仅4日有值5,其余为null。请问如何正确实现该功能?
更新:最终可行实现
由于未找到更优方案,我采用了以下实现,目前运行良好:
$user = Patient::where('id', $request->id)->with('clinic_session')->with('financial_movement')->first(); $a = 1; $end = $this->getDaysInMonth($current_month); $data = new Collection(); while ($a <= $end) { $date = new Carbon(date('Y').date('m').$a); $financial = $user->financial_movement->where('date', $date->toDateString())->first() ? $user->financial_movement->where('date', $date->toDateString())->first() : null; $data->push((object)[ 'day' => $a, 'session'=>$user->clinic_session->where('date', $date->toDateString())->first() ? $user->clinic_session->where('date', $date->toDateString())->first()->date_start : null, 'payment'=>$financial ? $financial->value : null, 'method'=>$financial ? $financial->method : null, 'notes'=>$financial ? $financial->notes : null, ]); $a++; } return view('backend.financials.show')->with('user', $user)->with('data', $data);
内容的提问来源于stack exchange,提问作者Filipe Madeira
相关产品推荐
相关产品推荐

