php - 尝试使用 PHP Laravel 对查询结果进行排序或排序
问题描述
我想根据start_date
. 但是,我不知道在哪里放置线
sortBY('start_time', 'asc')
或者
orderBy('start_date', 'asc')
这是我的完整代码:
@if(!empty($events) && $events->count() > 0)
@foreach($events as $event)
@if($event->is_published)
<div class="event-row">
<div style="display: table-cell; width: 20%;">
@if($event->uploads->count() > 0)
<img src="{!! $event->uploads->reverse()->first()->url !!}" alt="" title="" width="150"
height="150">
@endif
</div>
<div style="display: table-cell; width: 80%; vertical-align: top;">
<div>
<h3 style="margin-top: 3px; margin-bottom: 3px;">{!! $event->name !!}</h3><br/>
@if($event->start_time > 0)
<small style="font-size: 14px;">
{!! $event->start_time !!} - {!! $event->end_time !!}
</small>
@endif
<p style="margin-top: 6px; margin-bottom: 3px;">{!! $event->description !!}</p>
</div>
</div>
</div>
@endif
@endforeach
@else
Sorry, there are no events.
@endif
我发现我认为是查询:
namespace App\Models\General;
use App\Models\System\Upload;
use Illuminate\Database\Eloquent\Model;
/**
* Class Session
* package App.
*/
class Event extends Model
{
protected $fillable = ['name', 'description', 'start_time', 'end_time', 'is_published'];
public function uploads()
{
return $this->morphMany(Upload::class, 'uploadable');
}
}
这是查询吗?
解决方案
在刀片文件中使用动态属性时要小心。您不希望您的表示层意外地执行 SQL 查询。
也就是说,$builder->orderBy()将排序应用于 SQL 查询。当你做$builder->get()
你得到的是Eloquent的Support\Collections子类。Support\Collections 有一个方法可以让 Php 执行排序。sortBy()
只要有可能,就让 SQL 完成这项工作。
推荐阅读
- python - 如何在 OpenCv 中使用单应矩阵拼接两个图像?
- javascript - React-Router useHistory 抛出 TypeError
- javascript - 如何使用日期 ID 从数组中删除并单击?
- flutter - Github Actions Flutter CI 错误:没有匹配的 NDK 版本
- android - 无法在片段中显示图像
- python - 安装 flask-mysqldb 给出“mysql_config not found”
- javascript - 如何使用 react-router 制作“404 - Not Found”页面/路由?
- matlab - 使用加载的 TFORM 结构运行 tforminv
- python-3.x - 将输入值作为参数传递给另一个线程中的函数
- c++ - C++ 问题:为什么用大括号括起来的初始化器列表不能在类中工作?