Laravel查询:添加自定义功能,例如软删除 [英] Laravel Queries: Adding custom feature like Soft Deletes

查看:87
本文介绍了Laravel查询:添加自定义功能,例如软删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

All of my tables have a column called isTest. What I want is to be able to set a switch so that my code will either include all records in my queries or [more importantly] exclude all records where isTest is true.

我认为代码将类似于软删除,并包含类似于以下代码的sql代码: AND(isTest!= TRUE)雄辩的和查询生成器。

I imagine the code will work similarly to Soft Deletes and include sql code similar to: AND (isTest != TRUE) to SQL generated by Eloquent and the Query Builder.

我对口才事件并不是很熟悉,但是我发现了问题,它可能是开始的正确位置,但我希望在开始这条道路之前获得指导。另外,它没有有关查询生成器的信息。如果有人做了类似的事情,我会建议您。

I am not really familiar with Eloquent events, but I have found this question which might be the right place to start, but I am hoping for guidance before I start down that path. Also, that has no info about Query Builder. If someone has done something similar I would love some advice.

推荐答案

要查找全局范围,可以添加自定义范围,该范围将检查 isTest 值。

You are looking for Global scopes, you can add a custom scope which will check the isTest value.

<?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的工作方式一样。

When you have a lot of models, you want to make a trait of this code so you dont have to duplicate it all the time. Like how SoftDeletes work.

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

See docs for more info https://laravel.com/docs/5.8/eloquent#global-scopes

这篇关于Laravel查询:添加自定义功能,例如软删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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