use*_*492 2 php laravel laravel-5 laravel-notification
我正在 Laravel 5 中打印模型的通知:
@foreach ($booking->notifications as $notification)
<div class="message">
<div class="myMessage">
<p>{{ $notification->data[0])}}</p>
</div>
</div>
@endforeach
Run Code Online (Sandbox Code Playgroud)
这些通知按降序打印,有什么方法可以更改此设置,以便它们按升序打印?
Laravel 文档指出:
默认情况下,通知将按created_at时间戳排序
值得一提的是,该模型使用了多个通知类,因此我不确定这是否会影响排序行为?
@Peyman Seraj 在这里引领我走向正确的方向。
对于 Laravel 集合,您可以使用集合方法,因此我sortBy()在我的集合上使用了该方法:
@foreach ($booking->notifications->sortBy('created_at') as $notification)
Run Code Online (Sandbox Code Playgroud)
现在按升序打印数据。
小智 6
只是对这个问题感到困惑:通过遵循可通知的特征,我发现该关系已分配给它的顺序。
您可以在模型中覆盖它:
public function notifications()
{
return $this->morphMany(\Illuminate\Notifications\DatabaseNotification::class, 'notifiable')->orderByRaw('-read_at','DESC')->orderBy('created_at','DESC');
}
Run Code Online (Sandbox Code Playgroud)
就我而言,我会先阅读未读的内容,然后再阅读其余的内容。如果您想设置查询的排序,只需使用普通关系:
public function notifications()
{
return $this->morphMany(\Illuminate\Notifications\DatabaseNotification::class, 'notifiable');
}
Run Code Online (Sandbox Code Playgroud)