您可以通过三种方式做到这一点:
- A) 您可以将其应用于所有查询。
- B) 或者您可以在模型中创建单个范围并在查询中调用它。
- C) 或者您可以直接在您的查询中进行排序
A) 您可以将其应用于所有查询:
- 创建一个位于
/app/Scopes/SortByScope.php 的新范围文件
那么该文件 (SortByScope.php) 应该如下所示:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class SortByScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->orderBy('MyAttribute', 'DESC');
}
}
- 在你的模型中包含你头脑中的调用
<?php
namespace App;
use App\Scopes\SortedOrderScope;
...rest of your model...
- 在您的模型中包含以下内容:
/**
* Apply to all queries.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope(new SortByScope);
}
https://laravel.com/docs/master/eloquent#global-scopes
B) 或者您可以在模型中创建单个范围并在查询中调用它:
- 在您的模型中输入以下方法:
/**
* Scope a query to be sorted by MyAttribute
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSortedByMyAttribute($query)
{
$builder->orderBy('MyAttribute', 'DESC');
}
- 然后在您的查询中使用它:
$results = App\MyModel::sortedByMyAttribute()->get();
-或-
$results = App\MyModel::where('foo', '=', 'bar')->sortedByMyAttribute();
https://laravel.com/docs/master/eloquent#local-scopes
C) 或者您可以直接在查询中使用以下命令进行排序:
$results = App\MyModel::orderBy('MyAttribute', 'DESC')->get();