【问题标题】:Laravel Queries: Adding custom feature like Soft DeletesLaravel 查询:添加自定义功能,如软删除
【发布时间】:2019-08-06 19:48:48
【问题描述】:

我所有的表都有一个名为isTest 的列。我想要的是能够设置一个开关,以便我的代码要么包含我的查询中的所有记录,要么[更重要的是]排除所有 isTest 为真的记录。

我想代码的工作方式与软删除类似,并包含类似于:AND (isTest != TRUE) 到 Eloquent 和查询生成器生成的 SQL 的 sql 代码。

我对 Eloquent 事件不是很熟悉,但我发现 question 可能是正确的起点,但我希望在开始这条道路之前得到指导。此外,这没有关于查询生成器的信息。如果有人做过类似的事情,我会喜欢一些建议。

【问题讨论】:

标签: php laravel eloquent query-builder


【解决方案1】:

您正在寻找全局范围,您可以添加一个自定义范围来检查 isTest 值。

<?php


// Your custom scope
namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class IsTestScope 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->where('isTest', true);
    }
}


// Your model
namespace App;

use App\Scopes\IsTestScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        // Check for certain criteria, like environment
        if (App::environment('local')) {
            // The environment is local
            static::addGlobalScope(new IsTestScope);
        }
    }
}

当你有很多模型时,你想为这段代码创建一个特征,这样你就不必一直重复它。就像 SoftDeletes 的工作方式一样。

有关更多信息,请参阅文档https://laravel.com/docs/5.8/eloquent#global-scopes

【讨论】:

  • 这看起来正是我想要的。我会深入研究并检查出来。 谢谢!
猜你喜欢
  • 2021-10-03
  • 1970-01-01
  • 2012-05-19
  • 1970-01-01
  • 2015-01-15
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多