首页 > 解决方案 > 尝试使用 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');
    }
}

这是查询吗?

标签: phplaravel

解决方案


在刀片文件中使用动态属性时要小心。您不希望您的表示层意外地执行 SQL 查询。

也就是说,$builder->orderBy()将排序应用于 SQL 查询。当你做$builder->get()你得到的是Eloquent的Support\Collections子类。Support\Collections 有一个方法可以让 Php 执行排序。sortBy()

只要有可能,就让 SQL 完成这项工作。


推荐阅读