使用流明设置数据库中所有表的默认顺序



我有一个完整的应用程序,它是用流明编写的。申请已完成。我只需要为应用程序中的每个查询添加order by子句,这在某种程度上需要添加一些时间。在到处搜寻之后,我找到了以下方法。

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

我必须在每个模型中添加以上功能。这也是一个合理的解决方案,但我不想这样做。我想在一个地方添加这个功能,而不是像在任何服务提供商或其他地方那样在每个模型中添加。我不太熟悉这个框架。如果有人知道它的解决方案,请提供帮助。请注意,订单依据的时间戳字段名称具有不同的前缀。例如,tbl_created_at是名为column的表中的created_at字段,prnt_created_at字段是名为prints的表中创建的字段。谢谢你的帮助。

使其成为trait,在trait中,您仍然可以使用使用trait的类中的方法和变量:

<?php
namespace AppTraits;
trait DefaultOrderByDate
{
protected static function boot() {
parent::boot();
$field = parent::CREATED_AT;
static::addGlobalScope('order', function (Builder $builder) use ($field) {
$builder->orderBy($field, 'desc');
});
}
}

现在,在您的模型中,您可以使用它们,如:

<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use AppTraitsDefaultOrderByDate;
class SomeModel extends Model
{
use DefaultOrderByDate;
/**
* The name of the "created at" column.
*
* @var string
*/
const CREATED_AT = 'prnt_created_at';
/**
* The name of the "updated at" column.
*
* @var string
*/
const UPDATED_AT = 'prnt_updated_at';
}

这段代码是这个问题的无错误解决方案。

1:在的第一步创建一个Trait

<?php
namespace AppTraits;
use IlluminateDatabaseEloquentBuilder;
trait DefaultOrderByDate
{
protected static function boot() {
parent::boot();
$field = self::CREATED_AT;
static::addGlobalScope('order', function (Builder $builder) use ($field) {
$builder->orderBy($field, 'desc');
});
}
}

2:创建特征后创建模型

<?PHP
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use AppTraitsDefaultOrderByDate;
class SomeModel extends Model
{
use DefaultOrderByDate;
/**
* The name of the "created at" column.
*
* @var string
*/
const CREATED_AT = 'prnt_created_at';
/**
* The name of the "updated at" column.
*
* @var string
*/
const UPDATED_AT = 'prnt_updated_at';
}

最新更新