我通常使用模型上的全局范围按列对记录进行排序,但我需要按属性对其进行排序。
protected static function boot()
{
parent::boot();
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('MyAttribute', 'dsc');
});
}
我通常使用模型上的全局范围按列对记录进行排序,但我需要按属性对其进行排序。
protected static function boot()
{
parent::boot();
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('MyAttribute', 'dsc');
});
}
你的意思是
//...
->orderByRaw('(updated_at - created_at) desc')
//...
您可以通过三种方式做到这一点:
A)您可以将其应用于所有查询:
/app/Scopes/SortByScope.php
然后该文件(SortByScope.ph
p )应如下所示:
<?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();
我认为您的属性是访问器,它不是数据库中的真实列,因此您无法通过查询构建器或 eloquent 构建器直接访问它而无需离开数据库。
但是,您可以通过集合或 json 访问。所以如果要对记录进行排序,就需要使用sortBy
or sortByDesc
on collection。您需要从数据库中获取结果。所以你可以对它们进行排序。
Model::all()->sortBy('MyAttribute');
Model::all()->sortByDesc('MyAttribute');
您可以使用该方法withoutGlobalScope
从查询中删除范围:
Model::withoutGlobalScope('order')->orderBy('attribute', 'order')->get();
否则,您可以删除所有全局范围:
Model::withoutGlobalScopes()->orderBy('attribute', 'order')->get();
您可以在此处阅读更多信息Removing Global Scopes
:https ://laravel.com/docs/6.x/eloquent