Laravel Eloquent将列'archived_at'视为'deleted_at'

时间:2014-04-28 21:52:26

标签: php class laravel-4

我试图让Laravel处理一个名为' archived_at'的新添加列。与对待' deleted_at'的方式相同。也就是说,当我运行查询时,除非我明确告知,否则我不希望它接收任何存档记录(即Invoices :: onlyArchived() - > paginate())。换句话说,archived_at行为应该模仿Laravel中内置的软删除行为。

我看到Laravel的Builder和Model类中内置了软删除功能。这就是我到目前为止所拥有的:

  1. 扩展Model类并在new中添加archived_at功能 类。
  2. 更新app / config.php别名,如下所示:
  3.     // 'Eloquent'        => 'Illuminate\Database\Eloquent\Model',
        'Eloquent'        => 'CoreExtensions\Model',
    

    我似乎无法弄清楚如何扩展Builder类并强制Laravel从扩展的Builder类中读取。如果我能走得那么远,我可以弄清楚剩下的。有什么建议?提前谢谢!

2 个答案:

答案 0 :(得分:3)

您可能只需要扩展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();

答案 1 :(得分:0)

如果您正在运行Laravel 4.2,您可以查看这两个文件,我已根据内置的SoftDelete特性创建了自己的特征。 (它比上面的答案灵活得多。)

  • 照亮/数据库/锋/ SoftDeletingScope.php
  • 照亮/数据库/锋/ SoftDeletingTrait.php

http://laravel.io/forum/08-14-2014-add-filter-to-builder-on-a-custom-method-call