0

我通常使用模型上的全局范围按列对记录进行排序,但我需要按属性对其进行排序。

protected static function boot()
{
  parent::boot();
  static::addGlobalScope('order', function (Builder $builder) {
      $builder->orderBy('MyAttribute', 'dsc');
  });
}
4

4 回答 4

0

你的意思是

//...
->orderByRaw('(updated_at - created_at) desc')
//...
于 2020-01-15T20:34:49.217 回答
0

您可以通过三种方式做到这一点:

  • A)您可以将其应用于所有查询。
  • B)或者您可以在模型中创建单个范围并在查询中调用它。
  • C)或者您可以直接根据您的查询进行排序

A)您可以将其应用于所有查询:

  1. 创建一个新的范围文件位于/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');
    }
}
  1. 在你的模型中包括你头脑中的呼叫
<?php

namespace App;

use App\Scopes\SortedOrderScope;

...rest of your model...
  1. 在您的模型中包含以下内容:
    /**
     * 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)或者您可以在模型中创建单个范围并在查询中调用它:

  1. 在您的模型中输入以下方法:
    /**
     * 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');
    }
  1. 然后在您的查询中使用它:
$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();
于 2020-01-16T05:19:14.710 回答
0

我认为您的属性是访问器,它不是数据库中的真实列,因此您无法通过查询构建器或 eloquent 构建器直接访问它而无需离开数据库。

但是,您可以通过集合或 json 访问。所以如果要对记录进行排序,就需要使用sortByor sortByDescon collection。您需要从数据库中获取结果。所以你可以对它们进行排序。

Model::all()->sortBy('MyAttribute');
Model::all()->sortByDesc('MyAttribute');
于 2020-01-16T02:14:39.063 回答
0

您可以使用该方法withoutGlobalScope从查询中删除范围:

Model::withoutGlobalScope('order')->orderBy('attribute', 'order')->get();

否则,您可以删除所有全局范围:

Model::withoutGlobalScopes()->orderBy('attribute', 'order')->get();

您可以在此处阅读更多信息Removing Global Scopeshttps ://laravel.com/docs/6.x/eloquent

于 2020-01-15T20:25:52.013 回答