Laravel 4: How to add scope to DB::table?

后端 未结 4 1953
北荒
北荒 2021-01-12 18:38

With Eloquent models adding scopes is easy:

public function scopeMyScope($query)
{
   // Do stuff to that $query
}

But how to add scope to

4条回答
  •  独厮守ぢ
    2021-01-12 19:05

    You could create a custom class that passes all functions to the DB facade exept your custom queries. Like this:

    exitCalls = ['get', 'find', 'pluck', 'first', 'value', 'chunk', 'chunkById', 'count', 'max', 'avg', 'exists', 'doesntExist'];
        }
    
        public function __call($name, $arguments)
        {
            $result = call_user_func_array([self::$instance->db, $name], $arguments);
    
            if (in_array($name, $this->exitCalls)) {
                return $result;
            }
    
            return self::$instance;
        }
    
        public static function table($string)
        {
            if (self::$instance == null) {
                self::$instance = new CustomDB();
            }
    
            self::$instance->db = DB::table($string);
    
            return self::$instance;
        }
    
        public function myCustomQuery()
        {
             self::$instance->db->where('name','=','frank');
             return self::$instance;
        }
    }
    

    Now you can simply call:

    CustomDB::table('users')->myCustomQuery()->get();
    

提交回复
热议问题