laravel为模型中所有查询统一添加WHERE条件


    在使用laravel开发web系统的过程,需要在model处为该模型统一添加一个条件或者多个条件,研究了一个laravel的模型类,发现model中有个方法是构建查询的,方法如下:

/**
 * Register the global scopes for this builder instance.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $builder
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function registerGlobalScopes($builder)
{
    foreach ($this->getGlobalScopes() as $identifier => $scope) {
        $builder->withGlobalScope($identifier, $scope);
    }

    return $builder;
}

我们只需要在model里面修改这个方法的实现就可以
例如User
class Users extends Model
{
    protected $table = 'users';

    protected $hidden = [

    ]
    foreach ($this->getGlobalScopes() as $identifier => $scope) {
        $builder->withGlobalScope($identifier, $scope);
    }
    //这里就可以随便添加统一的条件了
    $builder->where('channel_id','=',1);
    return $builder;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM