Laravel Queries: Adding custom feature like Soft Deletes

可紊 提交于 2019-12-13 05:06:04

问题


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.

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.


回答1:


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);
        }
    }
}

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.

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



来源:https://stackoverflow.com/questions/55187553/laravel-queries-adding-custom-feature-like-soft-deletes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!