zoukankan      html  css  js  c++  java
  • laravel为模型中所有查询统一添加WHERE条件

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

    /**
     * Register the global scopes for this builder instance.
     *
     * @param  IlluminateDatabaseEloquentBuilder  $builder
     * @return IlluminateDatabaseEloquentBuilder
     */
    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;
    }
  • 相关阅读:
    2016/3/10 Java 错题
    2016/3/9 Java 错题集
    Java Socket 编程实验总结
    CSU 1290
    CSU 1307
    CSU 1060
    Problem B SPOJ DCEPC11I
    activemq 学习系列(二) 常用配置
    activemq 学习系列(一) 详细入门使用
    MySql 用户创建与授权
  • 原文地址:https://www.cnblogs.com/weishanyun/p/11207095.html
Copyright © 2011-2022 走看看