Laravel默认顺序 [英] Laravel default orderBy

查看:203
本文介绍了Laravel默认顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种干净的方法可以使某些模型按默认的顺序由属性排序? 可以通过扩展laravel的QueryBuilder来工作,但是要这样做,您必须重新连接其一些核心功能-不好的做法.

Is there a clean way to enable certain models to be ordered by a property by default? It could work by extending the laravel's QueryBuilder, but to do so, you'll have to rewire some of it's core features - bad practice.

原因

这样做的主要目的是-我的一个模型被许多其他模型重用,现在您必须一遍又一遍地求助于该顺序.即使为此使用闭包-您仍然必须调用它.能够应用默认排序会更好,因此,使用此模型且不提供自定义排序选项的每个人都会收到按默认选项排序的记录.这里不是使用存储库的选择,因为它很容易加载.

The main point of doing this is - one of my models get's heavily reused by many others and right now you have to resort the order over and over again. Even when using a closure for this - you still have to call it. It would be much better to be able to apply a default sorting, so everyone who uses this model, and does not provide custom sorting options, will receive records sorted by the default option. Using a repository is not an option here, because it get's eager loaded.

解决方案

扩展基本模型:

protected $orderBy;
protected $orderDirection = 'ASC';

public function scopeOrdered($query)
{
    if ($this->orderBy)
    {
        return $query->orderBy($this->orderBy, $this->orderDirection);
    }

    return $query;
}

public function scopeGetOrdered($query)
{
    return $this->scopeOrdered($query)->get();
}

在您的模型中:

protected $orderBy = 'property';
protected $orderDirection = 'DESC';

// ordering eager loaded relation
public function anotherModel()
{
    return $this->belongsToMany('SomeModel', 'some_table')->ordered();
}

在您的控制器中:

MyModel::with('anotherModel')->getOrdered();
// or
MyModel::with('anotherModel')->ordered()->first();

推荐答案

是的,您需要扩展Eloquent才能始终将其作为任何查询的标准配置.当您需要对查询添加order by语句时,怎么了?这是最干净的方法,即,您无需解开" Eloquent即可按自然顺序获得结果.

Yes you would need to extend Eloquent to always do this as standard for any query. What's wrong with adding an order by statement to the query when you need it ordered? That is the cleanest way, ie, you dont need to 'unhack' Eloquent to get results by natural order.

MyModel::orderBy('created_at', 'asc')->get();

除了最接近您想要的东西之外,还要在模型中创建查询范围.

Other than that the closest thing to what you want would be to create query scopes in your models.

public function scopeOrdered($query)
{
    return $query->orderBy('created_at', 'asc')->get();
}

然后您可以调用ordered作为方法而不是get来检索已排序的结果.

You can then call ordered as a method instead of get to retrieve your ordered results.

$data = MyModel::where('foo', '=', 'bar')->ordered();

如果您希望跨不同的模型使用此方法,则可以创建一个基类,然后将其扩展到您想要访问该范围方法的模型.

If you wanted this across different models you could create a base class and just extend it to the models you want to have access to this scoped method.

这篇关于Laravel默认顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆