我正试图让Laravel像对待"deleted_at"一样对待一个名为"archived_at"的新添加列。也就是说,当我运行查询时,我不希望它拾取任何存档的记录,除非我明确告诉它(即Invoices::onlyArchived()->paginate())。换句话说,archived_at行为应该模仿Laravel中内置的软删除行为。
我看到了Laravel的Builder和Model类中内置的软删除功能。到目前为止,我拥有的是:
- 扩展Model类并在新中添加archived_at功能类
- 按如下方式更新app/config.php别名:
// 'Eloquent' => 'Illuminate'Database'Eloquent'Model', 'Eloquent' => 'CoreExtensions'Model',
我似乎不知道如何扩展Builder类并强迫Laravel从扩展的Builder类中读取。如果我能做到这一点,我可能会想出其他的办法。有什么建议吗?提前感谢!
您可能只需要扩展Eloquent并执行以下操作:
<?php
class BaseModel extends Eloquent {
public static function withArchived()
{
return with(new static)->newQuery(true, true);
}
public static function onlyArchived()
{
return with(new static)->newQuery(false, false, true);
}
/**
* Get a new query builder for the model's table.
*
* @param bool $excludeDeleted
* @return 'Illuminate'Database'Eloquent'Builder|static
*/
public function newQuery($excludeDeleted = true, $excludeArchived = true, $onlyArchived = false)
{
$builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
// Once we have the query builders, we will set the model instances so the
// builder can easily access any information it may need from the model
// while it is constructing and executing various queries against it.
$builder->setModel($this)->with($this->with);
if ( ! $onlyArchived)
{
if ($excludeDeleted && $this->softDelete)
{
$builder->whereNull($this->getQualifiedDeletedAtColumn());
}
if ($excludeArchived)
{
$builder->whereNull('archived_at');
}
}
else
{
$builder->whereNotNull('archived_at');
}
return $builder;
}
}
然后你可能能够:
Invoices::onlyArchived()->paginate();
Invoices::withArchived()->where('customer_id', $customer_id)->paginate();
如果您正在运行Laravel 4.2,您可以查看这两个文件,我已经基于内置的SoftDelete特性创建了自己的特性。(它比上面的答案灵活得多。)
- Illuminate/Database/Eloquent/SoftDeletingScope.php
- Illuminate/Database/Eloquent/SoftDeletingTrait.php
http://laravel.io/forum/08-14-2014-add-filter-to-builder-on-a-custom-method-call