[英]laravel how to sort by year, month and date
我对 laravel 真的很陌生,所以如果我说了一些愚蠢的话,我很抱歉,但我想根据 boletines model 的 created_at 列制作一个手风琴。 现在我有一个在视图中使用查询的半工作代码,但我的一个朋友说这不是一个好习惯。 当我尝试添加过滤器时它也不起作用,因为当我将 whereYear() 添加到集合时它会损坏。
我希望它看起来像这样在此处输入图像描述
这就是我在 controller 中所拥有的
public function boletinesAlertas()
{
$monthsArray = ['01' => 'enero', '02' => 'febrero', '03' => 'marzo', '04' => 'abril', '05' => 'mayo', '06' => 'junio', '07' => 'julio', '08' => 'agosto', '09' => 'septiembre', '10' => 'octubre', '11' => 'noviembre', '12' => 'dciembre'];
return view('private.boletinesAlertas', ['boletines' => new Boletines(), 'monthsArray' => $monthsArray]);
}
在我看来我有这个 frankencode
@foreach ($years = getDates($boletines->pluck('created_at'), 0, 4) as $year)
{{$year}}
@foreach($months= getDates($boletines->whereYear('created_at', $year)->pluck('created_at'), 5,2) as $month)
{{$monthsArray[$month]}}
@foreach($days = getDates($boletines->whereYear('created_at', $year)->whereMonth('created_at', $month)->pluck('created_at'),8,2) as $day)
{{$day}}
<table>
<tr>
<th>nombre</th>
</tr>
@foreach ($bolestines->whereDate('created_at', $year . '-' . $month . '-' . $day)->get() as $boletin)
<tr>
<td>{{$boletin->name}}</td>
</tr>
@endforeach
</table>
@endforeach
@endforeach
@endforeach
getDates 是我创建的一个助手 function,它采用 created_at 和 2 个值来通过裁剪字符串来获取月份或日期。
有一个更好的方法吗? 当我尝试在 controller 中添加过滤器 function 时,它不仅看起来很糟糕,而且整个事情都停止了工作,而且由于某种原因我只显示了第一个月的条目
您正在尝试的可以通过收集方法来实现。 是的,您应该尝试在 controller 方法中进行所有数据操作。
视图应该只负责格式化和显示数据。
试试下面的,看看这是否是你想要的
public function boletinesAlertas()
{
$monthsArray = [
'01' => 'enero',
'02' => 'febrero',
'03' => 'marzo',
'04' => 'abril',
'05' => 'mayo',
'06' => 'junio',
'07' => 'julio',
'08' => 'agosto',
'09' => 'septiembre',
'10' => 'octubre',
'11' => 'noviembre',
'12' => 'dciembre'
];
$data = Boletines::get()->groupBy([
function($item){
return Carbon::parse($item->created_at)->format('Y');
},
function($item){
return Carbon::parse($item->created_at)->format('m');
},
function($item){
return Carbon::parse($item->created_at)->format('d');
}
]);
return view('private.boletinesAlertas', [
'data' => $data,
'monthsArray' => $monthsArray
]);
}
@foreach ($data as $year => $yearRows)
{{$year}}
@foreach($yearRows as $month => $monthRows)
{{$monthsArray[$month]}}
@foreach($monthRows as $day => $rows)
{{$day}}
<table>
<tr>
<th>nombre</th>
</tr>
@foreach ($rows as $boletin)
<tr>
<td>{{$boletin->name}}</td>
</tr>
@endforeach
</table>
@endforeach
@endforeach
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.